controllerr
@RunWith(SpringRunner.class) @SpringBootTest(classes=StaticcacheApplication.class)//不在同级别目录的话需要参数指定启动类的path @WebAppConfiguration //调用javaWEB的组件,比如自动注入ServletContext Bean等等 @AutoConfigureMockMvc public class BaseTest { @Autowired protected MockMvc mockMvc; /* @Autowired protected WebApplicationContext webApplicationConnect; @Before public void setUp() throws Exception { mockMvc = MockMvcBuilders.webAppContextSetup(webApplicationConnect).build(); } */ @Test public void echoTest(){ System.out.println("========"); } }
public class ControllerTest extends BaseTest { @Test public void testIndex() throws Exception { /* perform:执行一个RequestBuilder请求,会自动执行SpringMVC的流程并映射到相应的控制器执行处理; get:声明发送一个get请求的方法。MockHttpServletRequestBuilder get(String urlTemplate, Object... urlVariables):根据uri模板和uri变量值得到一个GET请求方式的。另外提供了其他的请求的方法,如:post、put、delete等。 param:添加request的参数,如上面发送请求的时候带上了了pcode = root的参数。假如使用需要发送json数据格式的时将不能使用这种方式,可见后面被@ResponseBody注解参数的解决方法 andExpect:添加ResultMatcher验证规则,验证控制器执行完成后结果是否正确(对返回的数据进行的判断); andDo:添加ResultHandler结果处理器,比如调试时打印结果到控制台(对返回的数据进行的判断); andReturn:最后返回相应的MvcResult;然后进行自定义验证/进行下一步的异步处理(对返回的数据进行的判断) */ MockHttpServletResponse response = mockMvc.perform(MockMvcRequestBuilders.get("/index") //请求的url,请求的方法是get .contentType(MediaType.TEXT_HTML) //请求参数格式 .param("address", "合肥").param("age", "20") //请求参数数据 .accept(MediaType.TEXT_HTML)) .andExpect(MockMvcResultMatchers.status().isOk()) //返回的状态是200 .andReturn().getResponse(); System.out.println(response.getContentAsString()); //请求数据是json Map<String, Object> map = new HashMap<>(); map.put("address", "合肥啊"); map.put("age", 11); String params = JSON.toJSONString(map); RequestBuilder request = MockMvcRequestBuilders.get("/index").contentType(MediaType.APPLICATION_JSON).accept(MediaType.APPLICATION_JSON).content(params); MvcResult mvcResult = mockMvc.perform(request).andReturn(); int status = mvcResult.getResponse().getStatus(); Assert.assertTrue("错误,正确的返回值为200", status == 200); System.out.println(mvcResult.getResponse().getContentAsString()); }
错误
org.springframework.web.util.NestedServletException: Request processing failed; nested exception is java.lang.IllegalStateException: Optional int parameter 'age' is present but cannot be translated into a null value due to being declared as a primitive type. Consider declaring it as object wrapper for the corresponding primitive type. 貌似不可一世使用int??