简体   繁体   中英

Adding Custom Messages to JUnit4 Style Exception Tests

I have the following test:

@Test(expected=ArithmeticException.class) 
   public void divideByZero() {
   int n = 2 / 1;
}

as seen here .

I would like to add a message that will print if this test fails.

For instance if I was doing an Assertion test, I would do the following to add a message:

@Test public void assertFail(){
    Assert.fail("This is the error message I want printed.");
    Assert.assertEquals(true, false);
}

The second example should print out "This is the error message I want printed.". How do I set the first example message text?

Maybe @Rule annotation should help. Into your unit test class add sth like this:

import org.junit.Rule;
import org.junit.rules.MethodRule;
import org.junit.runners.model.Statement;
import org.junit.runners.model.FrameworkMethod;
import org.junit.internal.runners.model.MultipleFailureException;
...
@Rule
public MethodRule failureHandler = new MethodRule()
{
    @Override
    public Statement apply(final Statement base, FrameworkMethod method, Object target)
    {
        return new Statement()
        {
            @Override
            public void evaluate() throws Throwable
            {
                List<Throwable> listErrors = new ArrayList<Throwable>();
                try
                {
                    // Let's execute whatever test runner likes to do
                    base.evaluate();
                }
                catch (Throwable testException)
                {
                    // Your test has failed. Store the test case exception
                    listErrors.add(testException);                        
                    // Now do whatever you need, like adding your message,
                    // capture a screenshot, etc.,
                    // but make sure no exception gets out of there -
                    // catch it and add to listErrors
                }
                if (listErrors.isEmpty())
                {
                    return;
                }
                if (listErrors.size() == 1)
                {
                    throw listErrors.get(0);
                }
                throw new MultipleFailureException(listErrors);
            }
        };
    }
};

Instead of collecting all the exceptions in listErrors you may consider wrapping testException with your exception with additional message and just throwing it.

If you are willing to use catch-exception instead of JUnit's built-in exception handling mechanisms, then your problem can be easily solved:

catchException(myObj).doSomethingExceptional();
assertTrue("This is the error message I want printed.",
           caughtException() instanceof ArithmeticException);

我不认为您可以轻松地做到这一点 ,但是这个人似乎已经在解决这个问题上做了部分努力。

I recommend instead naming the test to make it obvious what the test is testing, so when some of your tests fail, they tell you what the problem is. Here's an example using the ExpectedException rule:

@RunWith(JUnit4.class)
public class CalculatorTest {
  @Rule
  public ExpectedException exception = ExpectedException.none();

  @Test
  public void divisionByZeroShouldThrowArithmeticException() {
    Calculator calculator = new Calculator();

    exception.expect(ArithmeticException.class);
    calculator.divide(10, 0);
  }
}

For details on ExpectedException , see this article and the ExpectedException JavaDoc

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM