Reputation: 343
I am writing a series of test cases for a class with a few methods like:
public ServiceResponse getListOfGroups() {
ServiceResponse serviceResponse = new ServiceResponse();
try{
Slf4JStopWatch sw = new Slf4JStopWatch("GetListOfGroups", log, DEBUG_LEVEL);
List<Group> Groups = Arrays.asList(restTemplate.getForObject(getGroupServiceURL(), Group[].class));
sw.stop();
serviceResponse.setData(Groups);
} catch(ServiceException ex) {
serviceResponse.setErrorObject(ex.getErrorObject());
}
return serviceResponse;
}
The problem I am having is the fact that the restTemplate
is @autowired
from the actual implementation of the class (and therefore returning null when called in the unit test perspective). How would I go about writing a proper test case for these methods?
Here is what I have tried so far:
@Test
public void testGetListOfGroups() {
//TODO
ServiceResponse resp = new ServiceResponse();
Mockito.when(uwsci.getListOfGroups()).thenReturn(resp); //uwsci is my mocked object
assertTrue(uwsci.getListOfGroups() == resp);
}
I feel that this defeats the point of unit testing as it is just returning what I told it to and not really doing anything else.
Upvotes: 1
Views: 1954
Reputation: 692171
Since you chose field injection, the only way to inject a mock dependency in your object is to use reflection. If you had used constructor injection instead, it would be as easy as
RestTemplate mockRestTemplate = mock(RestTemplate.class);
ClassUnderTest c = new ClassUnderTest(mockRestTemplate);
Fortunately, Mockito makes that possible using its annotations support:
@Mock
private RestTemplate mockRestTemplate;
@InjectMocks
private ClassUnderTest classUnderTest;
@Before
public void prepare() {
MockitoAnnotations.initMocks(this);
}
Upvotes: 5