Spring中的单元测试
需要引入依赖
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.11</version>
<!-- 表示开发的时候引入,发布的时候不会加载此包 -->
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>4.0.2.RELEASE</version>
<scope>test</scope>
</dependency>
你也可以编写基类,然后具体业务类继承,你也可以直接怼,这里我就规范一下,先写基类
BaseTest.java如下,其中@Before和@After注解都是junit提供的,其含义写在代码的注释中了:
@RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration({"classpath:spring-mvc.xml","classpath:spring-mybatis.xml"}) public class BaseTest { @Before public void init() { //在运行测试之前的业务代码 } @After public void after() { //在测试完成之后的业务代码 } }
编写具体测试类
写完测试基类后,就可以开始写真正的单元测试了,下面是一个简单的示例:
public class HelloTest extends BaseTest { @Test public void getTicketInfo() { System.out.println("hello"); }
我们可以看到在IDEA中可以直接对单元测试的某个方法进行运行,不用编译项目和启动服务器就可以达到对业务代码的功能测试,可见其便利程度。
SpringBoot中的单元测试
SpringBoot中使用Junit和SpringMVC基本类似,只需要改动一些配置即可。
加入依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-test</artifactId>
<version>1.5.2.RELEASE</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>4.3.7.RELEASE</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>test</scope>
</dependency>
编写测试基类
@RunWith(SpringRunner.class) @SpringBootTest public class BaseTest { @Before public void init() { } @After public void after() { } }