These slides are up on GitHub!
jeffsheets/JavaTesting2013Slides
//Setup your Eclipse Favorites for code suggestions
import static org.junit.Assert.assertEquals;
/* ... */
assertEquals(2013, result.getYear().intValue());
assertEquals("JunitMotors", result.getMake().getName());
assertEquals(make.getId(), result.getMake().getId());
assertEquals(car.getDescription(), result.getDescription());
        
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.is;
import static org.junit.Assert.assertThat;
/* ... */
assertThat(result.getYear().intValue(), is(equalTo(2013)));
assertThat(result.getMake().getName(), is("JunitMotors"));
assertThat(result.getMake().getId(), is(make.getId()));
assertThat(result.getDescription(), is(car.getDescription()));
//containsString
//equalToIgnoringCase
          
assertThat(result, not(nullValue()));
assertThat(result, hasSize(original.size() + 1));
//This requires overridden provider.equals method
assertThat(result, hasItem(provider));
          
import static com.sheetsj.test.matchers.CustomMatchers.isStringInjected;
/* ... */
assertThat(anotherProperty, isStringInjected());
          
import static org.fest.assertions.Assertions.assertThat;
/* ... */
assertThat(demoUser.getEmail()).isEqualTo(userDetails.getUsername());
assertThat(demoUser.getPassword()).isEqualTo(userDetails.getPassword());
assertThat(hasAuthority(userDetails, demoUser.getRole()));
          
//Don't copy this!
@Test(expected=IndexOutOfBoundsException.class)
public void testIndexOutOfBoundsException() {
    Object a = service.getAllResults().get(2);
    Object b = service.getAllForA(a).get(2);
}
          
@Rule
public ExpectedException thrown = ExpectedException.none();
public void shouldThrowExceptionWhenUserNotFound() {
  thrown.expect(UsernameNotFoundException.class);
  thrown.expectMessage("not found");  //NOTE: something funny here
  
  when(accountRepositoryMock.findByEmail("user@example.com")).thenReturn(null);
  
  userService.loadUserByUsername("user@example.com");
}
          
public static void expect(String message, ExpectedException thrown)
{
  thrown.expect(BusinessValidationException.class);
  thrown.expectMessage(equalTo(message));
}
/** From UserServiceTest.java */
public void shouldThrowBusinessExceptionWhenUsernameTooShort() {
  //Uses custom expect matcher using equalTo() instead of containsString()
  expect("username", "username.too.short", thrown, "ab");
  
  userService.loadUserByUsername("ab");
}
          
private WorkItemRepository workItemRepository = mock(WorkItemRepository.class);
private WorkItemService service = new WorkItemService(workItemRepository);
/* .. inside a test method .. */
when(workItemRepository.findAll()).thenReturn(allWorkItems);
          
@RunWith(MockitoJUnitRunner.class)
public class WorkItemServiceTest {
  @Mock
  private WorkItemRepository workItemRepository;
  
  @InjectMocks
  private WorkItemService service = new WorkItemService();
}
          
@InjectMocks
@Spy
private WorkItemService service = new WorkItemService();
/* ... in test method ... */
doReturn(expectedList).when(service)
     .selectWorkItemsByMakeAndYear("bmw", "2008", allWorkItems);
     
Collection<WorkItem> results = service.findAllByMakeAndYear("bmw", "2008");
//Showing nested matchers in contains and sameInstance
assertThat(results, contains(sameInstance(expected)));
          
@ContextConfiguration(loader=AnnotationConfigContextLoader.class, 
             classes={RootConfig.class, PersistenceConfig.class})
@ActiveProfiles("test")
public abstract class IntegrationTestBaseClass extends 
                  AbstractTransactionalJUnit4SpringContextTests {
                  
}
          
public class WorkItemRepositoryIT extends IntegrationTestBaseClass {
  List<WorkItem> original = workItemRepository.findAll();
  
  Manufacturer make = manufacturerRepository.save(new Manufacturer("JUnitMake"));
  Car car = carRepository.save(new Car(2013, make, "JunitModel", "LT FWD 3.6L V6 DOHC 24V"));
  Provider provider = providerRepository.save(new Provider("Junit Tire Shop", "Shadow Lake"));
  
  WorkItem workItem = new WorkItem(car, new Date(), "Oil Change", provider, 18123L, 60.12, "Took 1:45 so got free oil change coupon");
  workItem = workItemRepository.save(workItem);
  
  List<WorkItem> result = workItemRepository.findAll();
}
          
public class PropertiesIT extends IntegrationTestBaseClass {
  @Value("${another.property}")
  private String anotherProperty;
  
  @Test
  public void testAnotherProperty() {
    assertThat(anotherProperty, isStringInjected());
  }
}
          
public class UserServiceIT extends IntegrationTestBaseClass {
  @Autowired
  private UserService userService;
  
  @Test
  public void testPropertyIsInjected() {
    assertThat(userService.getAnotherProperty(), isStringInjected());
  }
}
          
<properties>
  <spock.version>0.7-groovy-2.0</spock.version>
  <groovy.version>2.0.7</groovy.version>
</properties>
          
  
    
      
        org.codehaus.gmaven 
        gmaven-plugin 
        [1.5,) 
        
          testCompile 
          
         
       
       
         
       
     
   
 
          
class WorkItemServiceSpecTest extends Specification {
  def service = new WorkItemService()
  def "getYearAsString works for simple case"() {
    given: 'a normal date'
    def date = Date.parse("MM/dd/yyyy", "08/01/2013")
    
    when: 'getYearAsString is called'
    def result = service.getYearAsString(date)
    
    then: 'year is correct on result'
    result == "2013"
  }
}
          
def "getYearAsString works for simple case using expect block"() {
  given: 'a normal date'
  def date = Date.parse("MM/dd/yyyy", "08/01/2013")
  
  expect: 'getYearAsString is correct when called'
  service.getYearAsString(date) == "2013"
}
          
class WorkItemServiceSpecTest extends Specification {
  def service = new WorkItemService()
  def workItemRepository = Mock(WorkItemRepository)
  def setup() {
    service.workItemRepository = workItemRepository
  }
}
          
def "findAllByMakeAndYear works with mocks"() {
  given: 'a bunch of work items'
  List<WorkItem> allWorkItems = buildAllWorkItems()
  
  when: 'findAllByMakeAndYear is called'
  def results = service.findAllByMakeAndYear('ford', '2013')
  
  then: 'results are correct'
  1 * workItemRepository.findAll() >> allWorkItems
  results.containsAll allWorkItems[2,4]
}
          
/** not a good pattern. just showing it is possible */
def "findAllByMakeAndYear with many tests at once"() {
  given: 'a bunch of work items'
  List<WorkItem> allWorkItems = buildAllWorkItems()
  _ * workItemRepository.findAll() >> allWorkItems
  
  expect: 'findAllByMakeAndYear is called and has correct results'
  service.findAllByMakeAndYear('ford', '2013').containsAll(
     allWorkItems[2,4])
  service.findAllByMakeAndYear('ford', '2012').containsAll(
     allWorkItems[0..1])
  service.findAllByMakeAndYear('chevy', '2013').empty
  !service.findAllByMakeAndYear('ford', '2014')
}
          
def "findAllByMakeAndYear with many tests at once but multiple blocks"() {
  given: 'a bunch of work items'
  List allWorkItems = buildAllWorkItems()
  
  when: 'findAllByMakeAndYear is called for Ford and 2013'
  def results = service.findAllByMakeAndYear('ford', '2013')
  
  then: 'results are correct'
  1 * workItemRepository.findAll() >> allWorkItems
  results.containsAll allWorkItems[2,4]
  
  when: 'findAllByMakeAndYear is called for Ford and 2012'
  results = service.findAllByMakeAndYear('ford', '2012')
  
  then: 'results are correct'
  1 * workItemRepository.findAll() >> allWorkItems
  results.containsAll allWorkItems[0..1]
}
 
          
@Unroll
def "getYearAsString with #inputDate returns #result"
                                (String inputDate, String result) {
expect: 'getYearAsString is correct when called'
  service.getYearAsString(
              Date.parse("MM/dd/yyyy", inputDate)) == result
              
  where:
  inputDate    | result
  "01/01/1999" | "1999"
  "02/01/2000" | "2000"
  "03/01/199"  | "199"
  '03/01/2013' | '2013'	
}
          
def "findAll workItems and Save showing how the old method works"() {
  //...
  
  when: 'workItem saved, and results retrieved'
  WorkItem workItem = new WorkItem(car, new Date(), "Oil Change", provider, 18123L, 60.12, "Took 1:45 so got free oil change coupon");
  workItem = workItemRepository.save(workItem);
  List<WorkItem> result = workItemRepository.findAll();
  
  then: 'size was incremented'
  result.size() == old(workItemRepository.findAll()).size() + 1
}
          
@ContextConfiguration(loader=AnnotationConfigContextLoader, 
                      classes=[RootConfig, PersistenceConfig])
@Transactional
abstract class IntegrationSpecBaseClass extends Specification {
}
          
  expect: 'findAllByMakeAndYear returns correct results'
  that result1, containsInAnyOrder(allWorkItems[2], allWorkItems[4])
  that result2, containsInAnyOrder(allWorkItems[0], allWorkItems[1])
  that result3, empty()
  that result4, empty()
          
expect: 'findAllByMakeAndYear returns correct results'
result1.containsAll allWorkItems[2,4]
result2.containsAll(allWorkItems[0..1])
result3.empty
!result4
          
public void testGetMessage() {
  mockServer.expect(requestTo("http://google.com"))
    .andExpect(method(HttpMethod.GET))
    .andRespond(withSuccess("resultSuccess", MediaType.TEXT_PLAIN));
    
  String result = simpleRestService.getMessage();
  
  mockServer.verify();
  assertThat(result, allOf(containsString("SUCCESS"), 
                           containsString("resultSuccess")));
}