【问题标题】:Junit 4 ExpectedException.expectMessage should fail the test, and it doesn'tJunit 4 ExpectedException.expectMessage 应该没有通过测试,但它没有
【发布时间】:2017-04-16 13:29:34
【问题描述】:

我有以下课程:

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);
}

问题是测试 2 中的 expectMessage 是假的,为了便于讨论,实际预期的消息是 exceptionString 3,但测试并没有失败,尽管预期的消息与实际的消息不同。 它变得更奇怪了——如果我向 expectMessage 提供诸如“fdsfsdfsdfsdfsdfsdthe”之类的乱码消息——那么测试确实失败了:

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

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

我错过了什么吗?

【问题讨论】:

  • ExpectedException 仅包含 1 个预期异常。你不能像这样重复使用它。

标签: java exception junit java-8


【解决方案1】:

ExpectedException 仅包含 1 个预期异常。

你不能像这样重复使用它。要么:

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

【讨论】:

  • 我选择了第一个,就是这样
  • @SockworkOrange 我怀疑你现在的意思是第二个;我刚刚编辑以添加一个新的。
猜你喜欢
  • 1970-01-01
  • 2019-02-16
  • 2011-01-12
  • 2021-07-10
  • 1970-01-01
  • 1970-01-01
  • 2020-08-08
  • 2014-04-23
相关资源
最近更新 更多