JUnit4 fail() is here, but where is pass()?

后端 未结 6 948
闹比i
闹比i 2020-12-14 05:39

There is a fail() method in JUnit4 library. I like it, but experiencing a lack of pass() method which is not present in the library. Why is it so?

6条回答
  •  暗喜
    暗喜 (楼主)
    2020-12-14 06:03

    I think that this question is a result of a little misunderstanding of the test execution process. In JUnit (and other testing tools) results are counted per method, not per assert call. There is not a counter, which keeps track of how many passed/failured assertX was executed.

    JUnit executes each test method separately. If the method returns successfully, then the test registered as "passed". If an exception occurs, then the test registered as "failed". In the latter case two subcase are possible: 1) a JUnit assertion exception, 2) any other kind of exceptions. Status will be "failed" in the first case, and "error" in the second case.

    In the Assert class many shorthand methods are avaiable for throwing assertion exceptions. In other words, Assert is an abstraction layer over JUnit's exceptions.

    For example, this is the source code of assertEquals on GitHub:

    /**
     * Asserts that two Strings are equal.
     */
    static public void assertEquals(String message, String expected, String actual) {
        if (expected == null && actual == null) {
            return;
        }
        if (expected != null && expected.equals(actual)) {
            return;
        }
        String cleanMessage = message == null ? "" : message;
        throw new ComparisonFailure(cleanMessage, expected, actual);
    }
    

    As you can see, in case of equality nothing happens, otherwise an excepion will be thrown.

    So:

    assertEqual("Oh!", "Some string", "Another string!");
    

    simply throws a ComparisonFailure exception, which will be catched by JUnit, and

    assertEqual("Oh?", "Same string", "Same string");
    

    does NOTHING.

    In sum, something like pass() would not make any sense, because it did not do anything.

提交回复
热议问题