(j) 单元测试断言和错误信息?

(j)Unit testing assertions and error messages?

我目前正在测试一个方法,姑且称之为testedMethod()

方法体如下所示

private testedMethod(List<Protocoll> protocolList) {
    //so something with the protocolList
    if (something) && (somethingElse) {
        Assert.isFalse(areTheProtocollsCorrect(p1, p2), "Error, the protocols are wrong");
    }

    if (somethingCompeletlyElse) && (somethingElse) {
        Assert.isFalse(areTheProtocollsExactlyTheSame(p1, p2), "Error, the protocols are the same");
    }
}

来自 Assert.class 的附加代码:

为假:

public static void isFalse(boolean condition, String descr) {
    isTrue(!condition, descr);
}

为真:

public static void isTrue(boolean condition, String descr) {
    if (!condition) {
        fail(descr);
    }
}

失败:

public static void fail(String descr) {
    LOGGER.fatal("Assertion failed: " + descr);
    throw new AssertException(descr);
}

测试该方法应该正确执行的操作已完成。但我想测试这些断言。这个断言是代码的重要部分,我想看看当我向它提供错误数据时该方法是否抛出这些错误。我怎样才能使用 JUnit 做到这一点?

首先,我目前正在使用 JUnit,您不应该编写自己的 assert*fail 方法:它们已经包含在 Assert class.

无论如何,如果你想测试你的断言,你必须编写两种测试用例:正面案例和负面(失败)案例:

@Test
public void positiveCase1()
{
    // Fill your input parameters with data that you know must work:
    List<Protocoll> protocolList=...
    testedMethod(protocolList);
}

@Test
public void positiveCase2()
{
    ...
}

@Test(expected=AssertException.class)
public void negativeCase1()
{
    // Fill your input parameters with data that you know must NOT work:
    List<Protocoll> protocolList=...
    testedMethod(protocolList);
}

@Test(expected=AssertException.class)
public void negativeCase2()
{
    ...
}

Test 注释中的 expected 参数使 JUnit 检查是否引发了该类型的异常。否则,测试标记为 failed.

但我还是坚持认为最好使用JUnit标准。