JUnit 5

测试

<dependency>
    <groupId>org.junit.jupiter</groupId>
    <artifactId>junit-jupiter</artifactId>
    <version>5.8.0</version>
    <scope>test</scope>
</dependency>
import org.junit.jupiter.api.*;

public class MyTest {

    @BeforeAll
    static void init(){
        System.out.println("init");
    }
    @BeforeEach
    public void before(){
        System.out.println("before");
    }
    @AfterEach
    public void after(){
        System.out.println("after");
    }
    @Test
    public void testAdd(){
        Assertions.assertEquals(2,2);
        System.out.println("123");
    }

    @Test
    public void testAdd2(){
        Assertions.assertEquals(2,2);
        System.out.println("456");
    }
}

输出结果:

init
before
123
after
before
456
after

SpringBoot测试

  • @SpringBootTest会创建Spring boot上下文

  • @Autowired@SpyBean@MockBean,可以替换原来的Bean

    • 例如,在测试写数据库时,我们一般不直接写数据库,而是模拟该函数的运行。

    • @SpringBootTest
      public class MyTest{
          @SpyBean	//类似Autowired自动注入,但是是模拟的
          Svc svc1;
          @Test
          void t1(){
              when(svc1.add(1,1)).thenReturn(3);//模拟运行,并直接返回3
              int res = svc1.add(1,1);
              Assertions.assertEquals(res,3);
          }
      }
      
      
    • @MockBean默认模拟所有函数,@SpyBean只模拟使用when函数显式定义的函数。