Mockito and Deffered Result

Viewed 221

I have a spring based project and I am trying to improve the code coverage within it

I have the following block of code which uses a lambda on the defferedResult onCompletion method

        util.getResponse(userInfoDeferredResult, url, userName, password);

    userInfoDeferredResult.onCompletion(() -> {
        //the result can be a String or ErrorResponse
        //if ErrorResponse we don't want to cause ClassCastException and we don't need to cache the result
        if (userInfoDeferredResult.getResult() instanceof String){

            String response = (String) userInfoDeferredResult.getResult();

            cacheServices.addValueToCache(Service.USER_INFO_CACHE_NAME, corpId, response);              
        }
    });

I was wondering - is it possible to mock the contents of the onCompletion lambda using mockito or powerMockito?

4 Answers

Extract contents to new method:

if(userInfoDeferredResult.getResult() instanceof String) {
     String response = (String) userInfoDeferredResult.getResult();
     cacheServices.addValueToCache(Service.USER_INFO_CACHE_NAME, corpId, response);              
 }

Then test the method that way?

Generally I prefer not to change the service code for test code (for example extracting to method and make it public although it should be private). The onCompletion method is triggered when the completed of AsyncContext is called. So you can test in the following way:

@RunWith(SpringRunner.class)
@WebMvcTest(DeferredResultController.class)
public class DeferredResultControllerUnitTest {

    @MockBean
    CacheServices cacheServices;

    @Autowired
    private MockMvc mockMvc;

    @Test
    public void onCompletionTest() throws Exception {
        mockMvc.perform(get("/your_url"))
                .andDo(mvcResult -> mvcResult.getRequest().getAsyncContext().complete());
        Mockito.verify(cacheServices)
               .addValueToCache(Service.USER_INFO_CACHE_NAME, getExpextedCorpId(), getExpectedResponse());
        }
    }

Working github example here.

In contrast to @SpringBootTest, @WebMvcTest won't start the all Spring application context so it is more lighter.

Related