简体   繁体   English

将自定义消息添加到JUnit4样式异常测试

[英]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. 也许@Rule注释应该有所帮助。 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. 除了收集listErrors所有异常之外,您可以考虑将testException与带有附加消息的异常包装testException ,然后将其抛出。

If you are willing to use catch-exception instead of JUnit's built-in exception handling mechanisms, then your problem can be easily solved: 如果您愿意使用catch-exception而不是JUnit的内置异常处理机制,那么可以轻松解决您的问题:

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: 这是使用ExpectedException规则的示例:

@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 有关ExpectedException详细信息,请参阅本文ExpectedException JavaDoc。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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