我正在尝试使用 JUnit 为以下控制器代码编写测试用例。但是我得到了 500 个带有空指针异常的代码。(当我在 Postman 上测试时,它可以正常工作。)我认为 validEmp 的 HttpServeleRequest 请求可能会导致 testGetMethod 出现此空指针异常。任何人都可以告诉我在这里做错了什么以及如何解决这个问题?谢谢你的帮助:D登录服务public ReturnParam validEmp(HttpServletRequest request, String locale, String empKey, String accessToken) throws Exception { ReturnParam rp = new ReturnParam(); rp.setFail("not available"); return rp;}登录控制器@RequestMapping(value = "/valid", method = RequestMethod.GET, produces = "application/json; charset=UTF-8")public @ResponseBody ReturnParam validEmp(HttpServletRequest request, @RequestParam(value = "locale", required = true) String locale, @RequestParam(value = "empKey", required = true) String empKey, @RequestParam(value = "accessToken", required = true) String accessToken) throws Exception { return service.validEmp(request, locale, empKey, accessToken);}登录控制器测试public MockMvc mockMvc;private MediaType contentType = new MediaType(MediaType.APPLICATION_JSON.getType(), MediaType.APPLICATION_JSON.getSubtype(), Charset.forName("utf8"));public void testGetMethod(String url, String locale, String empKey, String acessToken) throws Exception { mockMvc.perform(get(url).param("locale", locale).param("empKey",empKey).param("accessToken", acessToken)) .andDo(print()) .andExpect(status().isOk());}
2 回答

慕慕森
TA贡献1856条经验 获得超17个赞
您需要在 LoginController 中模拟您的 LoginService。尝试将此类代码添加到 LoginControllerTest。
@Mock
private LoginService loginService;
@InjectMocks
private LoginController loginController;
@Before
public void init(){
MockitoAnnotations.initMocks(this);
mockMvc = MockMvcBuilders
.standaloneSetup(loginController)
.build();
}
添加回答
举报
0/150
提交
取消