英文:
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("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
得分: 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)
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论