[英]Unit test for Spring MVC Controllers that use annotation @RequestParam
如何为使用注释@RequestParam的Spring MVC控制器创建单元测试? 我已经为在handlerequest方法中使用HttpServletRequest对象的控制器创建了junit测试,但我正在寻找一种使用@RequestParam测试控制器的方法。
谢谢
@RequestMapping("/call.action")
public ModelAndView getDBRecords(@RequestParam("id") String id) {
Employee employee = service.retrieveEmployee(id);
}
这种控制器风格的魅力之一是您的单元测试不需要担心请求映射的机制。 他们可以直接测试目标代码,而不会对请求和响应对象产生任何影响。
因此,将您的单元测试编写为就像任何其他类一样,并忽略注释。 换句话说,从测试中调用getDBRecords()
并传入id
参数。 记住,你不需要对Spring本身进行单元测试,你可以认为它有效。
还有另一类测试(“功能”或“接受”测试),一旦部署它就会测试应用程序(使用例如WebDriver,Selenium,HtmlUnit等)。 这是测试您的映射注释正在完成工作的地方。
使用集成测试(谷歌Spring MVC集成测试)
有点这个
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.test.IntegrationTest;
import org.springframework.boot.test.SpringApplicationContextLoader;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.web.WebAppConfiguration;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.context.WebApplicationContext;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = YourApplication.class, loader = SpringApplicationContextLoader.class)
@WebAppConfiguration
@IntegrationTest("server.port:0")
public class SampleControllerTest {
@Value("${local.server.port}")
protected int port;
@Autowired
protected WebApplicationContext context;
private RestTemplate restTemplate = new RestTemplate();
@Test
public void returnsValueFromDb() {
// you should run mock db before
String id = "a0972ca1-0870-42c0-a590-be441dca696f";
String url = "http://localhost:" + port + "/call.action?id=" + id;
ResponseEntity<String> response = restTemplate.getForEntity(url, String.class);
Assert.assertEquals(HttpStatus.OK, response.getStatusCode());
String body = response.getBody();
// your assertions here
}
}
试试它作为你的测试方法!
@Test
public void testgetDBRecords(){
MockMvc mockMvc = MockMvcBuilders.webAppContextSetup(wac).build();
mockMvc.perform(get("/call.action?id=id1234").andExpect(status().isOk())
}
或者,您可以使用_request = new MockHttpServletRequest();
和_request.setAttribute(“key”,“value”);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.