Wednesday, 15 August 2007

Mocking interfaces that use generics

Something that I had trouble today was writing a test case for an interface that uses generics. I wanted to mock out the object that uses the interface using EasyMock. Since I find examples are the best, here goes. First the interface under test then the test code.


public interface DataAccessService {
public <T> List<T> findResultsByNamedQuery(String namedQuery);
}

public class MyTest {
@Test
public UseMockDataSource() {
TomJones request = new TomJones();
List<TomJones> requests = new ArrayList<TomJones>();
requests.add(request);

// mock out the data source
DataAccessService mockDAS = createMock(DataAccessService.class);
requestPreProcessor.setDataAccessService(mockDAS);
expect(mockDAS.<TomJones> findResultsByNamedQuery("request.findByStatus")).andReturn(requests);
replay(mockDAS);
...
}
}


Through trial and error I figured out where to put the generic declaration. :-/

Update: I'm a dummy and forgot to escape the less than and greater than signs so they would show up in html. Ooops.

No comments:

Post a Comment