Tuesday, September 2, 2008

Unit testing hooray!

Slowly I'm getting more into unit testing. It's hard to enforce the discipline to write the tests during development because writing tests takes more time and managers don't like things taking time. But they should be written during development because:
a) That's when you are most into the problem and thus best able to write the test
b) It makes you think about the code you are writing, perhaps discovering bugs as you create them
c) After the fact - there is never time to write tests anyway so it won't happen

When unit tests have been written the benefits are so marvelous. You can re-run them any time and be be sure all your app is still ok. It takes away the fear of changing things because they might break, just run the tests and you are sure you didn't break anything. Beats manually re-testing by a mile.

Finally, I've been getting into EasyMock to mock out the dependencies of my classes. Works great once you get used to it. Say you have a Controller class that needs a Service to search for something:

class Controller {
private final SearchService searcher;
public Controller(SearchService searcher) {
this.searcher = searcher;
}
}

interface SearchService {
List doSearch(String query);
}

class SearchServiceImpl implements SearchService {
List doSearch(String query) {
// Searching code here
}
}


Now to unit test the Controller just mock the SearchService:

@Test
public void testController() {
SearchService searchMock = EasyMock.createMock(SearchService.class);
EasyMock.expect(searchMock.doSearch("something")).andReturn(isA(List.class));
EasyMock.replay(searchMock);
EasyMock.verify(searchMock);
}


And the test can run without an implementation needed. And as a bonus you can check if the mock is called in the expected way.

Btw, I have to find some code syntax highlighting for Blogger.

No comments: