spring boot单元测试

丶灬走出姿态 提交于 2019-12-23 03:13:29

JUnit使用

JUnit主要用于白盒测试和回归测试。

检测JUnit依赖

如果是Spring Boot项目默认已经加入了JUnit框架支持,可在pom.xml中查看:

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-test</artifactId>
    <scope>test</scope>
</dependency>

如果Maven项目中没有添加JUnit依赖,可参照如上代码,手动添加。

基础使用

简单的测试代码如下:

@RunWith(SpringRunner.class)
@SpringBootTest
public class SimpleTest {
    @Test
    public void doTest() {
        int num = new Integer(1);
        Assert.assertEquals(num, 1);
    }
}

注解说明

注解列表

@RunWith:标识为JUnit的运行环境;
@SpringBootTest:获取启动类、加载配置,确定装载Spring Boot;
@Test:声明需要测试的方法;
@BeforeClass:针对所有测试,只执行一次,且必须为static void;
@AfterClass:针对所有测试,只执行一次,且必须为static void;
@Before:每个测试方法前都会执行的方法;
@After:每个测试方法前都会执行的方法;
@Ignore:忽略方法;
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!