SpringBoot单元测试写法
涉及的依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<version>2.7.5</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.13.2</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter</artifactId>
<version>5.9.1</version>
<scope>test</scope>
</dependency>
方式一:junit4
import org.junit.Assert;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.test.context.junit4.SpringRunner;
@RunWith(SpringRunner.class)
@SpringBootTest
public class Junit4DemoTest {
@Autowired
JdbcTemplate jdbcTemplate;
@BeforeClass
public static void beforeClass1() {
System.out.println("在整个类中只执行一次,static修饰");
}
@Before
public void before1() {
System.out.println("每个test方法之前调用一次");
}
@Test
public void test1() {
System.out.println("jdbcTemplate = " + jdbcTemplate);
Assert.assertNotNull(jdbcTemplate);
}
}
方式二:junit5
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.jdbc.core.JdbcTemplate;
@SpringBootTest
public class Junit5DemoTest {
@Autowired
JdbcTemplate jdbcTemplate;
@BeforeAll
public static void beforeAll1() {
System.out.println("在整个类中只执行一次,static修饰");
}
@BeforeEach
public void beforeEach1() {
System.out.println("每个test方法之前调用一次");
}
@Test
public void test1() {
System.out.println("jdbcTemplate = " + jdbcTemplate);
Assertions.assertNotNull(jdbcTemplate);
}
}