简体   繁体   中英

Junit test with autowired fields

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.

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);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM