我正在嘗試使用 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
提交
取消