在Springboot中集成单元测试入门很简单,这里做个简单的记录,后续会针对不同的单元测试场景不断进行完善和记录,希望给需要的人一点帮助。
引入相应的依赖
在SprintBoot中引入单元测试依赖包很简单,一般在创建SpringBoot项目的时候就会自行引入单元测试的依赖包。
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
该依赖在引入时如果带上了exclusions的说明,需要根据情况自行删除。
入门示例
我们创建一个入门的Springboot项目(啥业务逻辑都没有!),我们以Service层为例,创建一个Service的服务TestService,然后定义两个业务方法,具体如下:
package com.majing.learning.springboot.junit.service;
import org.springframework.stereotype.Service;
@Service
public class TestService {
public void method1(){
System.out.println("TestService -> method1");
}
public void method2(){
System.out.println("TestService -> method2");
}
}
接下来看怎么对上面的TestService进行测试。
如果你用的是IDEA,那么创建单元测试很方便,如下图所示:
这样在src/test/java下就会生成一个单元测试类,相应的目录结构和src/main/java中的包名相同。
相应的测试类TestServiceTest的实现如下。
package com.majing.learning.springboot.junit.service;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.jupiter.api.*;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
@RunWith(SpringRunner.class)
@SpringBootTest
class TestServiceTest {
@Autowired
private TestService testService;
@BeforeAll
public static void beforeAll() {
System.out.println("TestServiceTest -> @BeforeAll");
}
@AfterAll
public static void afterAll() {
System.out.println("TestServiceTest -> @AfterAll");
}
@AfterEach
void tearDown() {
System.out.println("TestServiceTest -> @AfterEach");
}
@BeforeEach
void setUp() {
System.out.println("TestServiceTest -> @BeforeEach");
}
@Test
void method1() {
testService.method1();
}
@Test
void method2() {
testService.method2();
}
}
运行结果如下:
在上面的测试用例中,用了几个注解,@BeforeAll,@AfterAll,@BeforeEach,@AfterEach,@Test。
需要说明的是,最开始我用@Before,@After,@BeforeClass,@AfterClass,想实现在这个测试类的所有测试方法前/后执行,但是发现都没有实现。后来发现要实现这样的功能,需要使用@BeforeAll,@AfterAll这两个注解。如上图结果所示,@BeforeAll,@AfterAll,这两个注解只被执行了一次,符合期望。
未完待续
上面只是一个简单说明,后面会整理针对不同业务场景下该如何进行单元测试,会不断的补充和完善这篇文章,有兴趣的可以添加关注,谢谢。
待续。。。
来源:oschina
链接:https://my.oschina.net/u/4268886/blog/4302785