August 15, 2007

Blog has been moved

This post has been moved to blogspot. No further posts will be made to this location.

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.

Posted by jim at August 15, 2007 12:55 PM
Comments
Due to the proliferation of comment spam, I’ve had to close comments on this entry. If you would like to leave comment, please use one of my recent entries. Thank you and sorry for any inconvience caused.