Junit 5
跳到导航
跳到搜索
要是跟 Spring Boot 2 及以上用,那么已经在 spring-boot-starter-test 里间接依赖了,
测试基类使用 @SpringBootTest(classes = Application.class) 之后,其他测试类直接继承就可以了。
然后要注意的是,区别用 Junit 4 用的 @Test 注解来自 org.junit.Test,Junit 5 的 @Test 来自 org.junit.jupiter.api.Test,
然后如果要断言静态方法的调用:
public class MathUtils {
public static int add(int a, int b) {
return a + b;
}
}
import org.junit.jupiter.api.Test;
import org.mockito.MockedStatic;
import org.mockito.Mockito;
import static org.junit.jupiter.api.Assertions.*;
import static org.mockito.Mockito.*;
@ExtendWith(MockitoExtension.class)
public class StaticMockTest {
@Test
public void testMockStatic() {
try (MockedStatic<MathUtils> mockedMathUtils = mockStatic(MathUtils.class)) {
// 模拟MathUtils.add方法的返回值
when(MathUtils.add(1, 2)).thenReturn(5);
// 调用被测试的代码,假设此处有代码调用了MathUtils.add(1, 2)
int result = MathUtils.add(1, 2);
assertEquals(5, result);
// 验证MathUtils.add方法是否被调用了一次,参数为1和2
mockedMathUtils.verify(() -> MathUtils.add(1, 2));
}
}
}
需要再引入:
<dependency>
<groupId>org.mockito</groupId>
<artifactId>mockito-inline</artifactId>
<scope>test</scope>
</dependency>