-2

如果我有以下课程:

public class MyTest
{
   @Test
   public void testSomething()
   {
     Something myData = new Something();
     testAccordingToData(myData);
   }


   @Test
   public void testSomethingElse()
   {
     Something myOtherData = new Something("something else");
     testAccordingToData(myOtherData);
   }

   private void testAccordingToData(Something someData)
   {
     assertTrue(somedata.someField);
     assertEquals(someData.someField, someData.someOtherField);
     //and various other assertions based on someData
   }
}

断言会testAccordingToData()正常工作,还是只能从带有注释的方法中调用断言@Test

4

3 回答 3

3

这是 Assert 中最复杂的链。您可以看到它与注释无关,它会抛出一个 AssertionError ,这并不奇怪,因为这是在断言失败时它所做的。

static public void assertEquals(String message, Object expected,
                                Object actual) {
    if (equalsRegardingNull(expected, actual)) {
        return;
    } else if (expected instanceof String && actual instanceof String) {
        String cleanMessage = message == null ? "" : message;
        throw new ComparisonFailure(cleanMessage, (String) expected,
                (String) actual);
    } else {
        failNotEquals(message, expected, actual);
    }
}

检查与

private static boolean equalsRegardingNull(Object expected, Object actual) {
    if (expected == null) {
        return actual == null;
    }

    return isEquals(expected, actual);
}

呼吁失败

static private void failNotEquals(String message, Object expected,
                                  Object actual) {
    fail(format(message, expected, actual));
}

调用

static public void fail(String message) {
    if (message == null) {
        throw new AssertionError();
    }
    throw new AssertionError(message);
}
于 2013-10-14T01:45:31.893 回答
3

junit“断言”只是简单的方法调用。可以从任何地方调用它们。

于 2013-10-14T01:27:27.430 回答
1

创建自定义断言方法并不常见,但通常是明智的。通常将方法命名为assertFoo.

如今,人们可以创建一个自定义的 Hamcrest 匹配器。

最后,您在上面评论说希望查看所有失败断言的结果。在这种情况下,JUnit 4.8 及更高版本为您提供了解决方案。查看ErrorCollector @Rule

于 2013-10-14T01:38:23.627 回答