单元测试学习

一、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");

参考文献

Junit5
Mockito

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值