How to display an enum in a dropdown in Wicket

Its often useful to use an enum as the model for a dropdown (or radio group) in Wicket, but not immediately obvious how to handle the display of the values. Lets say I have an enum with three colors:

enum Color { RED, GREEN, BLUE };

I can hook this up to a dropdown with the following code:

<select wicket:id="color"/>

enum Color { RED, GREEN, BLUE };
private Color color = Color.GREEN;
add(new DropDownChoice<color>("color", new Model<color>(color), Arrays.asList(Color.values())));

However, that would display “RED”, “GREEN”, “BLUE”. I probably don’t want the dropdown to use the default toString() form of my enum declarations, but rather I want it to load translatable texts from property files.

To do this, I can use Wicket’s EnumChoiceRenderer as follows:

<select wicket:id="color"/>
enum Color { RED, GREEN, BLUE };
private Color color = Color.GREEN;
add(new DropDownChoice<color>("color", Arrays.asList(Color.values()), new EnumChoiceRenderer<color>(this)));
Color.RED=Red
Color.GREEN=Green
Color.BLUE=Blue

Now I get what I wanted – a dropdown displaying “Red”, “Green” and “Blue”.

Mockito

We just started using Mockito for unit testing of our Wicket applications. Its a great tool, allowing us to easily mock out our service layers on a test-by-test basis.

In the example below, we’re testing a page called ItemPage. It takes an id of an item to load – internally the page uses itemService.find(id) to load the item from the database. Using Mockito, we mock out the itemService.find call to return a test item.

public class TestItemPage extends WicketTestcase {
	private static final long serialVersionUID = 1L;

	@Test
	public void TestItemPage() {
		when(itemService.find(Mockito.anyInt())).thenAnswer(new Answer() {

			@Override
			public Item answer(InvocationOnMock invocation) throws Throwable {
				final int id = (Item) invocation.getArguments()[0];
				Item item = new Item(id);
				item.setTitle("test");
				item.setDeadline(new Date());
				return item;
			}
		});

		tester.startPage(new ItemPage(12345));
		tester.assertRenderedPage(ItemPage.class);
	}
}