Unit test service method not get called

Viewed 501

I am going to make a unit test. But I finally got 500 error, therefore I set the breakpoint and run the test in debug mode. Finally I found that the service method not get called and return null. I just want to know why it skipped the articleService.getInfo, then make the object become null, and finally get 500 error.

@RunWith(SpringRunner.class)
@SpringBootTest(classes = Controller.class)
@WebAppConfiguration
public class ControllerTest {
    
    private MockMvc mockMvc;
   
    @MockBean
    private TestService testService;
    
    
    @Autowired
    private WebApplicationContext wac;
    
    @Before
    public void setup() {
        mockMvc = MockMvcBuilders.webAppContextSetup(wac).build();
    }

@Test
public void testList() throws Exception{
    ObjectMapper mapper = new ObjectMapper();
    String jsonStr = Files.readString(Paths.get("src/test/resources/data/list.json"));
    BookMarkResponse response = mapper.readValue(jsonStr, BookMarkResponse.class);
    Mockito.when(bookmarkService.getDocument(Mockito.anyString(), Mockito.anyString(), Mockito.anyInt(), Mockito.anyInt(),
            Mockito.anyString(), Mockito.anyString(), Mockito.anyString())).thenReturn(response);
    
    MvcResult result = mockMvc.perform(get("/getData")  
          .param("Id",Id))
    .andExpect(MockMvcResultMatchers.status().isOk())
    .andDo(MockMvcResultHandlers.print())
    .andReturn();
    assertNotNull(result.getResponse().getContentAsString());
    }


@RequestMapping(method = RequestMethod.GET, value="/getData")
@ResponseBody
public RandomList getList(@RequestParam("Id") int Id) {
    Response bookmarkTest = new Response();
    cTest = bookmarkService.getDocument(string, string, string, string, string, string, string);
    if(cTest.getResponseStatus() != 1){
        bkmark.setCode("Error");
        return bkmark;
    }
    List<NBookMark> nbookMarks = new ArrayList<NBookMark>();
    if( cTest.getTotal() > 0){
        nbookMarks = convert2List(cTest);
        bkmark.setCode("OK");
    }
    bkmark.setBookmarks(nbookMarks);
    return bkmark;
}

public List<NBookMark> convert2List(BookMarkResponse input) {
    List<NBookMark> Bookmarks = new ArrayList<NBookMark>();
    List<BookMarkDocument> bookmarks = input.getBookmarks();
    for(BookMarkDocument item: bookmarks) {
        NBookMark tempMark = new NBookMark();
        tempMark.setArticleId(Long.toString(item.getArticleId()));
        Document object = articleService.getInfo(articleFolderPath, Long.toString(item.getArticleId()));
        if(bkMarksource == null) { //this line the object is keep null, cannot pass the null checking
            continue; 
        }

//Do some null checking here, but cannot passed, since the object get null
@Service
public class ArticleService {

public Document getInfo(String articleFolderPath, String articleId) {
    Document Document = null;
    StandardXStream standardXStream = new StandardXStream();
    standardXStream.processAnnotations(Document.class);
    String url = "www.testing.com";
    
    try {
        standardXStream.setClassLoader(Document.class.getClassLoader());
        Document = (Document) standardXStream.readFromUrlandFile(url, filePath, false);
    } catch (RuntimeException e) {
        logger.info(e);
    } catch (Exception e) {
        logger.error(e.getMessage(), e);
    }

    if(Document != null) {
        return Document;
    }else {
        return null;
    }
}
    

Is it possible to use Mockito.when...thenReturn(). To call the actual function?

Mockito.when(articleService.getInfo(Mockito.anyString(),Mockito.anyString())).thenReturn(articleService.getInfo("test","test")); 
1 Answers

You aren't showing how you create articleService, so I can only assume it is a mocked object.

Methods that are not mocked don't call the original method by default, they just return null. What you need to do to get it to call the original method is:

Instead of

ArticleService articleService = Mockito.mock(ArticleService.class)

create the mock object with the parameter Mockito.CALLS_REAL_METHODS

ArticleService articleService = Mockito.mock(ArticleService.class, Mockito.CALLS_REAL_METHODS)
Related