一、Junit5
1.1 Maven
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter</artifactId>
<version>5.6.2</version>
<scope>test</scope>
</dependency>
1.2注解学习
- @Test 标注为一个测试方法,无其属性
- @ParameterizedTest 测试函数参数
@ParameterizedTest
@ValueSource(strings = {"racecar", "radar", "Zhangxiaopiao"})
void palindromes(String candidate) {
assertTrue(StringUtils.isAllLowerCase(candidate));
}
- @RepeatedTest 重复测试,可以控制重复测试次数和输出信息
@BeforeEach
void beforeEach(TestInfo testInfo, RepetitionInfo repetitionInfo) {
int currentRepetition = repetitionInfo.getCurrentRepetition();
int totalRepetitions = repetitionInfo.getTotalRepetitions();
String methodName = testInfo.getTestMethod().get().getName();
log.info(String.format("About to execute repetition %d of %d for %s", //
currentRepetition, totalRepetitions, methodName));
}
@RepeatedTest(10)
void repeatedTest() {
System.out.println("zxp");
}
- @Order(1) 测试顺序
- @Disable 取消某个固定的测试
二、Mockito
模拟实际类行为并作出验证
- stubbing
mockedList.add("one");
mockedList.clear();
verify(mockedList).add("one");
verify(mockedList).clear();
verify(mockedList).size();
LinkedList mockedList = mock(LinkedList.class);
//stubbing
when(mockedList.get(0)).thenReturn("first");
when(mockedList.get(1)).thenThrow(new RuntimeException());
//following prints "first"
System.out.println(mockedList.get(0));
//following prints "null" because get(999) was not stubbed
System.out.println(mockedList.get(999) + "111");
//following throws runtime exception
System.out.println(mockedList.get(1));
- anyInt()与验证次数
//stubbing using built-in anyInt() argument matcher
when(mockedList.get(anyInt())).thenReturn("element");
mockedList.add("once");
verify(mockedList).add("once");
verify(mockedList, times(2)).add("once");
verify(mockedList, never()).add("never happened");
- 顺序
InOrder inOrder = inOrder(singleMock);
//following will make sure that add is first called with "was added first", then with "was added second"
inOrder.verify(singleMock).add("was added first");
inOrder.verify(singleMock).add("was added second");