Spring、Spring Boot 和 TestNG 测试指南 ( 6 )

2017 年 12 月 14 日 ImportNew

(点击上方公众号,可快速关注)


来源:chanjarster,

github.com/chanjarster/spring-test-examples


Spring Testing Framework提供了Spring MVC Test Framework,能够很方便的来测试Controller。同时Spring Boot也提供了Auto-configured Spring MVC tests更进一步简化了测试需要的配置工作。


本章节将分别举例说明在不使用Spring Boot和使用Spring Boot下如何对Spring MVC进行测试。


例子1:Spring


测试Spring MVC的关键是使用MockMvc对象,利用它我们能够在不需启动Servlet容器的情况下测试Controller的行为。


源代码SpringMvc_1_Test.java:


@EnableWebMvc

@WebAppConfiguration

@ContextConfiguration(classes = { FooController.class, FooImpl.class })

public class SpringMvc_1_Test extends AbstractTestNGSpringContextTests {

 

  @Autowired

  private WebApplicationContext wac;

 

  private MockMvc mvc;

 

  @BeforeMethod

  public void prepareMockMvc() {

    this.mvc = webAppContextSetup(wac).build();

  }

 

  @Test

  public void testController() throws Exception {

 

    this.mvc.perform(get("/foo/check-code-dup").param("code", "123"))

        .andDo(print())

        .andExpect(status().isOk())

        .andExpect(content().string("true"));

 

  }

 

}


在这段代码里,主要有三个步骤:


  1. 将测试类标记为@WebAppConfiguration

  2. 通过webAppContextSetup(wac).build()构建MockMvc

  3. 利用MockMvc对结果进行判断


例子2:Spring + Mock


在例子1里,FooController使用了一个实体FooImpl的Bean,实际上我们也可以提供一个Foo的mock bean来做测试,这样就能够更多的控制测试过程。如果你还不知道Mock那么请看Spring、Spring Boot 和 TestNG 测试指南 ( 4 )


源代码SpringMvc_2_Test.java:


@EnableWebMvc

@WebAppConfiguration

@ContextConfiguration(classes = { FooController.class })

@TestExecutionListeners(listeners = MockitoTestExecutionListener.class)

public class SpringMvc_2_Test extends AbstractTestNGSpringContextTests {

 

  @Autowired

  private WebApplicationContext wac;

 

  @MockBean

  private Foo foo;

 

  private MockMvc mvc;

 

  @BeforeMethod

  public void prepareMockMvc() {

    this.mvc = webAppContextSetup(wac).build();

  }

 

  @Test

  public void testController() throws Exception {

 

    when(foo.checkCodeDuplicate(anyString())).thenReturn(true);

 

    this.mvc.perform(get("/foo/check-code-dup").param("code", "123"))

        .andDo(print())

        .andExpect(status().isOk())

        .andExpect(content().string("true"));

 

  }

 

}


例子3:Spring Boot


Spring Boot提供了@WebMvcTest更进一步简化了对于Spring MVC的测试,我们提供了对应例子1的Spring Boot版本。


源代码BootMvc_1_Test.java:


@WebMvcTest

@ContextConfiguration(classes = { FooController.class, FooImpl.class })

public class BootMvc_1_Test extends AbstractTestNGSpringContextTests {

 

  @Autowired

  private MockMvc mvc;

 

  @Test

  public void testController() throws Exception {

 

    this.mvc.perform(get("/foo/check-code-dup").param("code", "123"))

        .andDo(print())

        .andExpect(status().isOk())

        .andExpect(content().string("true"));

 

  }

 

}


在这里,我们不需要自己构建MockMvc,直接使用@Autowired注入就行了,是不是很方便?


例子4:Spring Boot + Mock


这个是对应例子2的Spring Boot版本,源代码BootMvc_2_Test.java:


@WebMvcTest

@ContextConfiguration(classes = { FooController.class })

@TestExecutionListeners(listeners = MockitoTestExecutionListener.class)

public class BootMvc_2_Test extends AbstractTestNGSpringContextTests {

 

  @Autowired

  private MockMvc mvc;

 

  @MockBean

  private Foo foo;

 

  @Test

  public void testController() throws Exception {

 

    when(foo.checkCodeDuplicate(anyString())).thenReturn(true);

 

    this.mvc.perform(get("/foo/check-code-dup").param("code", "123"))

        .andDo(print())

        .andExpect(status().isOk())

        .andExpect(content().string("true"));

 

  }

 

}


参考文档


  • Loading a WebApplicationContext

    https://docs.spring.io/spring/docs/4.3.9.RELEASE/spring-framework-reference/html/integration-testing.html#testcontext-ctx-management-web

  • Spring MVC Test Framework

    https://docs.spring.io/spring/docs/4.3.9.RELEASE/spring-framework-reference/htmlsingle/#spring-mvc-test-framework

  • Spring MVC Official Sample Tests

    https://github.com/spring-projects/spring-framework/tree/master/spring-test/src/test/java/org/springframework/test/web/servlet/samples

  • Spring MVC showcase – with full mvc test

    https://github.com/spring-projects/spring-mvc-showcase

  • Auto-configured Spring MVC tests

    http://docs.spring.io/spring-boot/docs/1.5.4.RELEASE/reference/htmlsingle/#boot-features-testing-spring-boot-applications-testing-autoconfigured-mvc-tests

  • Spring Framework Testing

    http://docs.spring.io/spring/docs/4.3.9.RELEASE/spring-framework-reference/htmlsingle/#testing

  • Spring Boot Testing

    http://docs.spring.io/spring-boot/docs/1.5.4.RELEASE/reference/htmlsingle/#boot-features-testing

  • Spring Guides – Testing the Web Layer

    https://spring.io/guides/gs/testing-web/


系列



看完本文有收获?请转发分享给更多人

关注「ImportNew」,看技术干货

登录查看更多
0

相关内容

MVC 模式(Model-View-Controller)是软件工程中的一种软件架构模式,把软件系统分为三个基本部分:模型(Model)、视图(View)和控制器(Controller)。
【2020新书】使用高级C# 提升你的编程技能,412页pdf
专知会员服务
56+阅读 · 2020年6月26日
【实用书】Python机器学习Scikit-Learn应用指南,247页pdf
专知会员服务
258+阅读 · 2020年6月10日
Python导论,476页pdf,现代Python计算
专知会员服务
254+阅读 · 2020年5月17日
《代码整洁之道》:5大基本要点
专知会员服务
49+阅读 · 2020年3月3日
【干货】大数据入门指南:Hadoop、Hive、Spark、 Storm等
专知会员服务
94+阅读 · 2019年12月4日
计算机视觉最佳实践、代码示例和相关文档
专知会员服务
17+阅读 · 2019年10月9日
盘一盘 Python 系列特别篇 PyEcharts TreeMap
平均机器
17+阅读 · 2019年6月13日
手把手教你用Python实现“坦克大战”,附详细代码!
机器学习算法与Python学习
11+阅读 · 2019年6月8日
Github项目推荐 | pikepdf - Python的PDF读写库
AI研习社
9+阅读 · 2019年3月29日
34个最优秀好用的Python开源框架
专知
9+阅读 · 2019年3月1日
一份数据科学家必备的技能清单(附资源)
THU数据派
7+阅读 · 2018年5月29日
Spark App自动化分析和故障诊断
CSDN大数据
7+阅读 · 2017年6月22日
EfficientDet: Scalable and Efficient Object Detection
Arxiv
6+阅读 · 2019年11月20日
Arxiv
19+阅读 · 2018年5月17日
Arxiv
4+阅读 · 2016年12月29日
VIP会员
相关资讯
盘一盘 Python 系列特别篇 PyEcharts TreeMap
平均机器
17+阅读 · 2019年6月13日
手把手教你用Python实现“坦克大战”,附详细代码!
机器学习算法与Python学习
11+阅读 · 2019年6月8日
Github项目推荐 | pikepdf - Python的PDF读写库
AI研习社
9+阅读 · 2019年3月29日
34个最优秀好用的Python开源框架
专知
9+阅读 · 2019年3月1日
一份数据科学家必备的技能清单(附资源)
THU数据派
7+阅读 · 2018年5月29日
Spark App自动化分析和故障诊断
CSDN大数据
7+阅读 · 2017年6月22日
Top
微信扫码咨询专知VIP会员