且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何使用@PathVariable 对 Spring MVC 控制器进行单元测试?

更新时间:2023-09-17 11:33:28

从 Spring 3.2 开始,有一种适当的方法可以优雅而简单地测试这一点.您将能够执行以下操作:

As of Spring 3.2, there is a proper way to test this, in an elegant and easy way. You will be able to do things like this:

@RunWith(SpringJUnit4ClassRunner.class)
@WebAppConfiguration
@ContextConfiguration("servlet-context.xml")
public class SampleTests {

  @Autowired
  private WebApplicationContext wac;

  private MockMvc mockMvc;

  @Before
  public void setup() {
    this.mockMvc = webAppContextSetup(this.wac).build();
  }

  @Test
  public void getFoo() throws Exception {
    this.mockMvc.perform(get("/foo").accept("application/json"))
        .andExpect(status().isOk())
        .andExpect(content().mimeType("application/json"))
        .andExpect(jsonPath("$.name").value("Lee"));
  }
}

欲了解更多信息,请查看 http://blog.springsource.org/2012/11/12/spring-framework-3-2-rc1-spring-mvc-test-framework/

For further information, take a look at http://blog.springsource.org/2012/11/12/spring-framework-3-2-rc1-spring-mvc-test-framework/