【问题标题】:Junit test for catch block not throwing any exception after catching捕获块的 Junit 测试在捕获后不抛出任何异常
【发布时间】:2021-01-21 05:21:27
【问题描述】:

我必须为 catch 块编写 Junit 测试。但我无法确定我应该在这里断言什么。由于 func() 只捕获异常而不抛出任何我无法使用 Assertions.assertThatExceptionOfType() 断言的东西。我是 Junit 测试的新手,所以想不出其他任何东西。任何可能的方法来测试 catch 块接收到的异常类型。

方法

public void func() {
    try {
        int x = solve();
    } catch(Exception1 e) {
        log.warn("error", e);
    } catch(Exception2 e) {
        log.warn("error", e);
    }
}

private int solve() throws ExceptionName {
    //do something...
    throws new Exception("error occured");
    ...
}

【问题讨论】:

  • 这里,你没有调用 func 方法。你在 JUnit 中使用 Mockito 吗?
  • 正如我在当前示例中看到的,被测试的模块使用记录器来记录一些消息。您至少有两个选择: 1) 以这种方式配置记录器,以便您能够捕获和验证记录的消息。 2)使用记录器本身的模拟/存根并验证传递的(消息,异常)元组。
  • @dbl 日志将传递事件 ID,因此第一个选项是不可能的。如果我可以模拟记录器,那么我将如何获取异常类型,因为它捕获了多个异常。
  • 我不能给你更多的细节,因为我需要深入挖掘,但这里至少是一个起点 - stackoverflow.com/questions/8948916/…

标签: java spring unit-testing junit try-catch


【解决方案1】:

您可以更改solve() 方法的可见性并使用所有异常情况对其进行测试。例如将其更改为默认值

int solve() throws ExceptionName {

使用此方法将测试与类放在同一个包中,以便可以从测试中访问它。

更新

最好的方法是将代码更改为更易于测试,如上所示。 为了不更改代码,您可以使用this answer 的方式。这可能很棘手。使用 Mockito 和 PowerMockito,您可以控制何时创建 Exception1Exception2。根据这个你就知道执行了哪个catch语句。

在测试代码中可能是这样的:

@RunWith(PowerMockRunner.class)
@PrepareForTest({ Exception1.class, Exception2.class, MyClass.class })
public class TestClass {

    @Before
    public void setup() {
        Exception1 cutMock = Mockito.mock(Exception1.class);
        PowerMockito.whenNew(Exception1.class)
                .withArguments(Matchers.anyString())
                .thenReturn(cutMock);
    }

    @Test
    public void testMethod() {
        // prepare
        MyClasss myClass = new MyClass();

        // execute
        myClass.func();

        // checks if the constructor has been called once and with the expected argument values:
        String value = "abc";
        PowerMockito.verifyNew(Exception1.class).withArguments(value);
    }
}

【讨论】:

  • 不能仅出于测试目的更改可见性
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2020-05-13
  • 1970-01-01
  • 2016-02-17
  • 1970-01-01
  • 2014-04-25
  • 1970-01-01
  • 2013-06-24
相关资源
最近更新 更多