【问题标题】:Unit test service method not get called未调用单元测试服务方法
【发布时间】:2020-10-07 18:58:21
【问题描述】:

我要进行单元测试。但我最终得到 500 错误,因此我设置了断点并在调试模式下运行测试。最后我发现服务方法没有被调用并返回null。 我只是想知道为什么它跳过了articleService.getInfo,然后使对象变为null,最后得到500错误。

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

是否可以使用 Mockito.when...thenReturn()。调用实际函数?

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

【问题讨论】:

  • 展示你如何构建你的测试(你是否使用任何特殊的测试注释,如@WebMvcTest、@SpringBootTest?你是否使用任何运行器/扩展?你如何构建 MockMvc?。书签服务是如何初始化的? ) 所有这些都有细节问题,没有它们纯属猜测。

标签: java mockito


【解决方案1】:

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

未模拟的方法默认不调用原始方法,它们只是返回 null。要让它调用原始方法,您需要做的是:

代替

ArticleService articleService = Mockito.mock(ArticleService.class)

使用参数 Mockito.CALLS_REAL_METHODS 创建模拟对象

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

【讨论】:

  • 它不是模拟类。我只是显示类的代码,谢谢
猜你喜欢
  • 2021-01-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多