「测试」 - 单元测试 & JUnit 4忽略异常执行

按照正常的单元测试要求,一个case应该只有一个断言,不会出现多个断言在一个case中的场景,但是有时为了效率,希望多个断言都在case中执行,但是JUnit 4触发断言失败后,其他断言不会执行。

@Test
public void testIEEE754()
    double addRs = 0.05 + 0.01;
    double subRs = 1.0 - 0.42;
    double mulRs = 4.015 * 100;
    double divRs = 123.3 / 100;
    log.info("0.05 + 0.01 = {}", addRs);
    log.info("1.0 - 0.42 = {}", subRs);
    log.info("4.015 * 100 = {}", mulRs);
    log.info("123.3 / 100 = {}", divRs);
    Assert.assertEquals(0.06, addRs);
    Assert.assertEquals(1.42, subRs);
    Assert.assertEquals(401.5, mulRs);
    Assert.assertEquals(1.233, divRs);
}

一、 AssertJ 软断言。

@Test
public void testIEEE754()
    double addRs = 0.05 + 0.01;
    double subRs = 1.0 - 0.42;
    double mulRs = 4.015 * 100;
    double divRs = 123.3 / 100;
    log.info("0.05 + 0.01 = {}", addRs);
    log.info("1.0 - 0.42 = {}", subRs);
    log.info("4.015 * 100 = {}", mulRs);
    log.info("123.3 / 100 = {}", divRs);
    SoftAssertions softAssert = new SoftAssertions();
    softAssert.assertThat(addRs).isEqualTo(0.06);
    softAssert.assertThat(subRs).isEqualTo(1.42);
    softAssert.assertThat(mulRs).isEqualTo(401.5);
    softAssert.assertThat(divRs).isEqualTo(1.233);
    softAssert.assertAll();
}   

软断言允许执行下一步而不抛出异常,在末尾assertAll()方法中抛出所有收集错误。

org.assertj.core.api.SoftAssertionError: 
The following 4 assertions failed:
1) expected:<0.06[]> but was:<0.06[0000000000000005]>
at BigDecimalUtilTest.testIEEE754(BigDecimalUtilTest.java:32) expected:<0.06[]> but was:<0.06[0000000000000005]>
2) expected:<[1.42]> but was:<[0.5800000000000001]>
at BigDecimalUtilTest.testIEEE754(BigDecimalUtilTest.java:33) expected:<[1.42]> but was:<[0.5800000000000001]>
3) expected:<401.[5]> but was:<401.[49999999999994]>
at BigDecimalUtilTest.testIEEE754(BigDecimalUtilTest.java:34) expected:<401.[5]> but was:<401.[49999999999994]>
4) expected:<1.23[3]> but was:<1.23[29999999999999]>
at BigDecimalUtilTest.testIEEE754(BigDecimalUtilTest.java:35) expected:<1.23[3]> but was:<1.23[29999999999999]>

二、 ErrorCollector

@Rule
public ErrorCollector collector = new ErrorCollector();
@Test
public void testIEEE754A()
    double addRs = 0.05 + 0.01;
    double subRs = 1.0 - 0.42;
    double mulRs = 4.015 * 100;
    double divRs = 123.3 / 100;
    collector.checkThat(addRs, IsEqual.equalTo(0.06));
    collector.checkThat(subRs, IsEqual.equalTo(1.42));
    collector.checkThat(mulRs, IsEqual.equalTo(401.5));
    collector.checkThat(divRs, IsEqual.equalTo(1.233));
        throw new RuntimeException("Exception");