Been tinkering with the 1.8 release of Mockito and found an interesting new feature: support for a Behavior Driven Development syntax.
It’s pretty exciting the readable tests you can create with this new subclass. Here’s a quick example I whipped up during my Mockito presentation today:
package org.jamescarr.MockitoDemo.bdd;
import static org.junit.Assert.assertThat;
import static org.mockito.BDDMockito.given;
import org.hamcrest.BaseMatcher;
import org.hamcrest.Description;
import org.hamcrest.Matcher;
import org.jamescarr.MockitoDemo.stubs.Bar;
import org.jamescarr.MockitoDemo.stubs.Bartender;
import org.jamescarr.MockitoDemo.stubs.Drink;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.runners.MockitoJUnitRunner;
@RunWith(MockitoJUnitRunner.class)
public class BarSpec {
@Mock Bartender bartender;
private Bar bar;
@Before
public void before(){
bar = new Bar(bartender);
}
@Test
public void shouldGiveMeADrinkWhenIWalkIn(){
given(bartender.askForRandomDrink()).willReturn(Drink.MOJITO);
Drink drink = bar.buyDrink();
assertThat(drink, isMojito());
}
private Matcher isMojito() {
return new IsMojito();
}
}
class IsMojito extends BaseMatcher{
public boolean matches(Object item) {
return "BACARDI MOJITO".equals(((Drink)item).getType());
}
public void describeTo(Description description) {
description.appendText("This drink is not a mojito");
}
}


Why the ugly and verbose custom matcher?
Indeed… the custom matcher wasn’t really needed, however I was also illustrating Hamcrest matchers in the presentation as well.