天天看點

JUnit 注解@Rule的工作原理

Suppose you need to repeatedly execute some test method in your unit test case, for example, you would like to test getPrice based on the first set of test data 5 times in test method test1() while for the second set of test data, only one time should be executed.

The below class RepeatDemoOne is a bad example, where this special LOOP operation is mixed with test method implementation

JUnit 注解@Rule的工作原理

Ideally the test method should only contain the pure logic to operate on the method being tested. So we have a better solution RepeatDemoTwo:

It could easily be observed that now the test method test1 and test2 are rather clean: no more for LOOP and System.out.println exist any more.

JUnit 注解@Rule的工作原理
Instead, I put the LOOP logic and print out operation into class RepeatableRule which implements interface MethodRule. The concrete rule implementation is done by overriding method apply as below:
JUnit 注解@Rule的工作原理
JUnit 注解@Rule的工作原理
JUnit 注解@Rule的工作原理
Besides exception, we can also manually specify a sub string which is expected to appear in an error message, and add our custom error message in Junit report if a test method fails. See following code for example:

public class RuleWithException {
    @Rule
    public ExpectedException exp = ExpectedException.none();

    @Test
    public void expectMessage()
    {
        exp.expectMessage("Hello World");
        throw new RuntimeException("Hello World will throw exception.");
    }

    @Test
    public void expectCourse()
    {
        exp.expectCause(new BaseMatcher<IllegalArgumentException>()
        {

            public boolean matches(Object item)
            {
                return item instanceof IllegalArgumentException;
            }

            @Override
            public void describeTo(org.hamcrest.Description description) {
                description.appendText("Expected exception with type IllegalArgumentException "
                        + "raised in test method! ");
            }

        });
        
        Throwable cause = new IllegalArgumentException("Cause Test.");
        throw new RuntimeException(cause);
    }
}
      
JUnit 注解@Rule的工作原理
JUnit 注解@Rule的工作原理

繼續閱讀