猿问

使用 jUnit 测试 RESTful Api 时出现 java.lang

我正在尝试使用 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());

}


慕妹3146593
浏览 186回答 2
2回答

慕慕森

您需要在 LoginController 中模拟您的 LoginService。尝试将此类代码添加到 LoginControllerTest。@Mockprivate LoginService loginService;@InjectMocksprivate LoginController loginController;@Beforepublic void init(){    MockitoAnnotations.initMocks(this);    mockMvc = MockMvcBuilders            .standaloneSetup(loginController)            .build();}

温温酱

我认为问题不是请求,而是注入。根据您的堆栈跟踪,我会说该服务为空(控制器中的注入不起作用)
随时随地看视频慕课网APP

相关分类

Java
我要回答