Junit 4 ExpectedException.expectMessage应该通过测试失败,但事实并非如此

Soc*_*nge 2 java junit exception java-8

我有以下课程:

public class MyClassTest {
@Rule
public ExpectedException thrown = ExpectedException.none();

@Test
public void testMyMethod() throws Exception {
    // Test 1
    String[] args = ...;
    MyClass.myMethod(args);

    // Test 2
    thrown.expect(InvalidParamException.class);
    thrown.expectMessage("exceptionString 1");
    args = ...;
    MyClass.myMethod(args);

    // test 3
    thrown.expect(InvalidParamException.class);
    thrown.expectMessage("exceptionString 2");
    args = ...;
    MyClass.myMethod(args);
}
Run Code Online (Sandbox Code Playgroud)

问题是测试2中的expectMessage是错误的,为了讨论,实际预期的消息是exceptionString 3,但测试没有失败,尽管预期的消息与实际的消息不同.它变得更奇怪 - 如果我向expectMessage提供诸如"fdsfsdfsdfsdfsdfsdthe"之类的乱码信息 - 那么测试确实会失败:

java.lang.AssertionError:预期:( InvalidParamException和异常的实例,消息包含一个包含"fdsfsdfsdfsdfsdfsdthe"的字符串)但是:带有消息的异常,包含"fdsfsdfsdfsdfsdfsdthe"消息的字符串是"exceptionMessage3"

这是预期的行为 - 但是当我更改exceptionMessage3一点点,字母或两个,甚至发送一个空字符串时 - 测试根本不会失败.

我错过了什么吗?

And*_*ner 6

ExpectedException 只保留1个预期的例外.

你不能像这样重用它.或者:

  1. 将您的测试用例分成3个独立的测试用例;
  2. 有3个ExpectedException实例;
  3. 使用普通旧try/ catch;
  4. 如果您使用的是最新版本的Java(8+)和支持它的JUnit,请使用assertThrows(或expectThrows).