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:忽略方法;