Java测试

Java测试.

代码测试

命名约定

  • 类名以Test为后缀
  • 在测试方法中使用
    • should,比如ordersShouldBeCreated
    • Given[ExplainYourInput]When[WhatIsDone]Then[ExpectedResult]

JUnit

以Junit5为主。

常用注解

  • @Test()
  • @Tag("")
  • @Disabled(“reason”)
  • @DisplayName("")
  • @BeforeEach
  • @TestFactory

Junit4 格式:

  • @Ignore(“reason”)
  • @Test(timeout=10)

断言

  • assertTrue
  • assertEquals
  • assertNull
  • assertSame
  • assertTimeout
  • assertTimeoutPreemptively
  • assertAll 分组
  • expectThrows

参数化

@ParameterizedTest

支持4种方式的数据源:

  • @ValueSource
  • @EnumSource
  • @MethodSource
  • @CsvSource

运行

自定义运行:JUnitCore.runClasses()

执行顺序: @FixMethodOrder(MethodSorters.NAME_ASCENDING) 

// Test Suites,支持2种方式
@RunWith(JUnitPlatform.class)
@SelectPackages("com.xulizhao.junit5.demo")
@SelectClasses({OrderTest.class, ProductTest.class})
public class AllTests {}

AssertJ

assertj是一个fluent API的断言库

import static org.assertj.core.api.Assertions.*;

assertThat(frodo.getName()).isEqualTo("Frodo");
assertThat(frodo).isNotEqualTo(sauron);
assertThat(frodo.getName()).startsWith("Fro")
                           .endsWith("do")
                           .isEqualToIgnoringCase("frodo");
# 比较2List
assertThat(first).hasSameElementsAs(second);
assertThat(first).containsExatlyInAnyOrderElementsOf(second);

Hamcrest

assertThat(first,Matchers.containsInAnyOrder(second.toArray));

common-collections4

assertTrue(CollectionUtils.isEqualCollection(first, second));

JaCoCo

代码覆盖率测试

扩展阅读