我正在我的 spring 控制器中测试一个方法,当它到达 sendRequest 方法时,我得到了一个 url 的空指针。我的测试方法如下:
@Test
public void testShowForm() {
Map<String, Object> params = new HashMap<String, Object>();
params.put("email", "testemail");
params.put("accessCode", KeyGenerator.getKey64());
String result = sendRequest("/userInfo.htm", GET, userController, params);
assertNotNull(result);
}
我的助手类:
public class JUnitControllerHelper extends JUnitHelper {
@Autowired
protected JUnitDataHelper jUnitDataHelper;
@Autowired
protected JUnitServiceHelper jUnitServiceHelper;
@Autowired
protected ApplicationContext applicationContext;
protected final String GET = "GET";
protected final String POST = "POST";
protected MockHttpServletRequest request;
protected MockHttpServletResponse response;
protected HandlerAdapter handlerAdapter;
@Before
public void setUp() {
request = new MockHttpServletRequest();
response = new MockHttpServletResponse();
handlerAdapter = applicationContext.getBean(HandlerAdapter.class);
}
public String sendRequest(String url, String method, Object controller, Map<String, Object> params) throws Exception {
request.setRequestURI(url);
request.setParameters(params);
request.setMethod(method);
request.setContentType("application/json");
handlerAdapter.handle(request, response, controller);
return response.getContentAsString();
}
public static void assertSubmitSuccess(String json) {
if(!json.contains("\"success\":true"))
fail("Submit returned unexpected errors");
}
public static void assertSubmitError(String field, String json) {
if(!json.contains("\"success\":false") || !json.contains("\"errors\"") || !json.contains("\""+field+"\""))
fail("Submit did not return expected errors");
}
}
请求引用变量属于 MockHttpServletRequest 类,在我的控制器中它标有@RequestMapping(method = RequestMethod.GET, value = "/userInfo")
,任何帮助将不胜感激。
应用程序上下文.xml:
<import resource="classPath:springConfig/dao.xml"/>
<import resource="classPath:springConfig/database.xml"/>
<import resource="classPath:springConfig/service.xml"/>
<import resource="classPath:springConfig/validator.xml"/>
<import resource="data.xml"/>
<import resource="controller.xml"/>
<import resource="junit.xml"/>
</beans>`
我的所有测试都在一个测试目录中,在我的 controller.xml 中我有:
<bean id="userInfoController" class="com.ck.web.controller.UserController"/>
<bean class="org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping"/>
<bean id="jacksonMessageConverter" class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter"/></bean>
<bean class="org.springframework.web.servlet.mvc.AnnotationMethodHandlerAdapter"/></bean>`