使用注释的Spring MVC控制器的单元测试@RequestParam

使用注释的Spring MVC控制器的单元测试@RequestParam

问题描述:

如何为使用注释@RequestParam的Spring MVC控制器创建单元测试?我已经为在controllerrequest方法中使用HttpServletRequest对象的控制器创建了junit测试,但是我正在寻找一种使用@RequestParam测试控制器的方法。使用注释的Spring MVC控制器的单元测试@RequestParam

感谢

@RequestMapping("/call.action") 

public ModelAndView getDBRecords(@RequestParam("id") String id) { 

    Employee employee = service.retrieveEmployee(id); 

} 
+0

在这篇文章请看:http://stackoverflow.com/questions/861089/testing-spring-mvc-annotation-mapppings – McStretch 2010-11-05 18:52:28

一个这种风格控制器的魅力是你的单元测试并不需要担心的请求映射的机制。他们可以直接对目标代码进行测试,而不会与请求和响应对象混淆。

所以编写你的单元测试就好像它只是任何其他类一样,而忽略注释。换句话说,请从您的测试中调用getDBRecords()并传递id参数。记住,你不需要对Spring本身进行单元测试,你可以假设它是有效的。

还有另一类测试(“功能性”或“接受”测试),它在部署后测试应用程序(使用WebDriver,Selenium,HtmlUnit等)。 这个是测试你的映射注释在做这项工作的地方。

或者,你可以使用 _request =新MockHttpServletRequest();

and _request.setAttribute(“key”,“value”);

使用集成测试(谷歌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 
    } 

} 
+0

洛尔没有想通这个问题,5年前有人问。无论如何,也许有人觉得这很有用 – 2015-10-30 10:46:30

尝试,因为你的测试方法!

@Test 
    public void testgetDBRecords(){ 
     MockMvc mockMvc = MockMvcBuilders.webAppContextSetup(wac).build(); 
     mockMvc.perform(get("/call.action?id=id1234").andExpect(status().isOk()) 
    }