@Test 和Assertions添加了@Test注解后,可以使测试方法直接运行 Assertions类调用断言相关的静态方法
public class Test1 {
@Test
void fun1(){
int res = 1 + 1;
//断言Junit4.x是 Assert, 5.x版本更新为 Assertions
Assertions.assertEquals(3,res); //判断是否相等
Assertions.assertTrue(3 == res); //用布尔值的方式判断
}
}
@BeforeEach, @BeforeAll, @AfterEach, @AfterAllpublic class Test2 {
@BeforeAll
static void BeforeAll(){
System.out.println("init once");
}
@AfterAll
static void AfterAll(){
System.out.println("after once");
}
@BeforeEach
void BeforeEach(){
System.out.println("init");
}
@AfterEach
void AfterEach(){
System.out.println("after");
}
@Test
public void t1(){
System.out.println(123);
}
@Test
public void t2(){
System.out.println(456);
}
}
运行结果
init once
init
123
after
init
456
after
after once
@SpringBootTest 搭配 @Autowired使用添加@SpringBootTest注解与@Autowired搭配使用,可以使Service实现自动注入
@SpringBootTest
public class Test3 {
// @Test
// void t1(){
// int res = new Svc1().add(1,1); //此时需要new Service
// Assertions.assertEquals(2,res);
// }
@Autowired
Svc1 svc1; //Spring自动注入
@Test
void t1(){
int res = svc1.add(1,1);
Assertions.assertEquals(2,res);
}
}
@MockBean,@SpyBean搭配规则条件配置,如静态方法when()@MockBean 模拟操作,通常应用于涉及到对数据库等操作的测试
@SpyBean 根据配置规则执行,配置了规则就按照规则执行,否则不执行(此时等同于@MockBean)规则配置可以使用when()等静态方法(Mockito)
@MockBean demo@SpringBootTest
public class Test3 {
@MockBean
Svc1 svc1;
@Test
void t1(){
//Mock配置规则只指定了加法;
int res = svc1.add(1,1); //mock后res = 0
Assertions.assertEquals(2,res);
}
}
运行结果
org.opentest4j.AssertionFailedError:
Expected :2
Actual :0
@SpyBean demoimport static org.mockito.Mockito.when; //when方法
@SpringBootTest
public class Test3 {
@SpyBean //配置了规则就按照规则执行,没有配置就不执行
Svc1 svc1;
@Test
void t1(){
// Mock配置规则指定了1+1=3
when(svc1.add(1,1)).thenReturn(3);
int res = svc1.add(1,1);
Assertions.assertEquals(2,res); //
}
}
运行结果
org.opentest4j.AssertionFailedError:
Expected :2
Actual :3