我正在尝试使用Mockito测试springboot服务,但是从我的模拟服务中得到空响应 代码可以编译,服务也可以正常运行,但是测试案例由于模拟服务返回null而失败。
服务等级
@RestController
@RequestMapping(path = "/my-tracker")
public class MyTrackerController {
private static final Logger logger = LoggerFactory.getLogger(MyTrackerController .class);
@Autowired
private TrackerService trackerService;
@RequestMapping(value = "/track/{id}", method = RequestMethod.GET, produces = "application/json")
public String getTrackerDetails(@PathVariable("id") String id)
{
String response = trackerservice.track(id); // <= this is returning null
return response;
}
}
测试类
@RunWith(SpringRunner.class)
@WebMvcTest(value = MyTrackerController.class)
public class MyTrackerControllerTest {
@Autowired
private MockMvc mockMvc;
@MockBean
private TrackerService trackerService ;
@Test
public void getTrackerDetailsTest() throws Exception {
String response= "MyLocation";
Mockito.when(
trackerService.track(
Mockito.anyString())).thenReturn(response);
RequestBuilder requestBuilder = MockMvcRequestBuilders.get(
"/my-tracker/track/123").accept(
MediaType.APPLICATION_JSON);
MvcResult result = mockMvc.perform(requestBuilder).andReturn();
System.out.println(result.getResponse());
JSONAssert.assertEquals(response, result.getResponse()
.getContentAsString(), true);
}
}
任何帮助/建议都将受到高度赞赏。 使用的Springboot版本是2.3.0.RELEASE。
推荐撰写测试用例的博客:https://www.springboottutorial.com/unit-testing-for-spring-boot-rest-services
p.s。 :我能够从上述博客代码成功运行测试用例,但我的模拟服务返回null。除了spring-boot-starter-web和spring-boot-starter-test之外,也没有添加其他jars
答案 0 :(得分:0)
我可以考虑的一个原因:
根据getTrackerDetails的RequestMapping,期望将JSON字符串作为响应返回(产生= application / json)
尝试在测试用例中返回有效的JSON作为响应。
示例:
String response = "\"field\":\"value\"";