SpringBoot的测试类写法
使用SpringBoot 2.2.2.RELEASE
版本编写测试类。1.x
版本通常使用junit4
。
1.1 junit4
测试类写法
依赖的jar包
<!-- 最上方统一限制SpringBoot的版本 -->
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.2.2.RELEASE</version>
<relativePath/>
</parent>
<!-- 在<dependencies>里面加入下面两个jar包 -->
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
测试类写法
@RunWith(SpringRunner.class)
@SpringBootTest
public class SpringBootTests {
@Before
public void beforeTest() {
}
@Test
public void test1() {
}
}
1.2 junit5
测试类写法
相关jar包
<!-- 最上方统一限制SpringBoot的版本 -->
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.2.2.RELEASE</version>
<relativePath/>
</parent>
<!-- 在<dependencies>里面加入下面jar包 -->
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
<exclusions>
<exclusion>
<groupId>org.junit.vintage</groupId>
<artifactId>junit-vintage-engine</artifactId>
</exclusion>
</exclusions>
</dependency>
</dependencies>
测试类书写
@SpringBootTest
// 使用spring的测试框架
@ExtendWith(SpringExtension.class)
class SpringbootTests {
@BeforeEach // 类似于junit4的@Before
public void beforeTest(){
}
@Test
void test1(){
}
}