单元测试服务方法未被调用

huangapple go评论70阅读模式
英文:

Unit test service method not get called

问题

@RunWith(SpringRunner.class)
@SpringBootTest(classes = Controller.class)
@WebAppConfiguration
public class ControllerTest {
	
    // ... (other code)

    @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 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();
            Document object = articleService.getInfo(articleFolderPath, Long.toString(item.getArticleId()));
            if (object == null) {
                continue;
            }
            // Do some null checking here
        }
        // ...
    }
}
@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);
        }
    
        return document;
    }
}
// Is it possible to use Mockito.when...thenReturn() to call the actual function?
// The following line is not necessary, as Mockito.when().thenReturn() can't be used to directly call actual methods.
// Mockito.when(articleService.getInfo(Mockito.anyString(), Mockito.anyString())).thenReturn(articleService.getInfo("test", "test"));
英文:

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(&quot;src/test/resources/data/list.json&quot;));
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(&quot;/getData&quot;)	
.param(&quot;Id&quot;,Id))
.andExpect(MockMvcResultMatchers.status().isOk())
.andDo(MockMvcResultHandlers.print())
.andReturn();
assertNotNull(result.getResponse().getContentAsString());
}
@RequestMapping(method = RequestMethod.GET, value=&quot;/getData&quot;)
@ResponseBody
public RandomList getList(@RequestParam(&quot;Id&quot;) int Id) {
Response bookmarkTest = new Response();
cTest = bookmarkService.getDocument(string, string, string, string, string, string, string);
if(cTest.getResponseStatus() != 1){
bkmark.setCode(&quot;Error&quot;);
return bkmark;
}
List&lt;NBookMark&gt; nbookMarks = new ArrayList&lt;NBookMark&gt;();
if( cTest.getTotal() &gt; 0){
nbookMarks = convert2List(cTest);
bkmark.setCode(&quot;OK&quot;);
}
bkmark.setBookmarks(nbookMarks);
return bkmark;
}
public List&lt;NBookMark&gt; convert2List(BookMarkResponse input) {
List&lt;NBookMark&gt; Bookmarks = new ArrayList&lt;NBookMark&gt;();
List&lt;BookMarkDocument&gt; 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 = &quot;www.testing.com&quot;;
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(&quot;test&quot;,&quot;test&quot;)); 

答案1

得分: 1

你没有展示如何创建 articleService,所以我只能假设它是一个模拟对象。

那些没有被模拟的方法默认不会调用原始方法,它们只会返回空值。要使其调用原始方法,你需要进行以下操作:

不要使用:

ArticleService articleService = Mockito.mock(ArticleService.class)

使用带有参数 Mockito.CALLS_REAL_METHODS 来创建模拟对象:

ArticleService articleService = Mockito.mock(ArticleService.class, Mockito.CALLS_REAL_METHODS)
英文:

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)

huangapple
  • 本文由 发表于 2020年9月30日 16:33:01
  • 转载请务必保留本文链接:https://go.coder-hub.com/64133829.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定