Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/spring/13.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 捕获块的Junit测试在捕获后未引发任何异常_Java_Spring_Unit Testing_Junit_Try Catch - Fatal编程技术网

Java 捕获块的Junit测试在捕获后未引发任何异常

Java 捕获块的Junit测试在捕获后未引发任何异常,java,spring,unit-testing,junit,try-catch,Java,Spring,Unit Testing,Junit,Try Catch,我必须为catch块编写Junit测试。但我无法确定我应该在这里断言什么。由于func()只捕获异常而不抛出任何我无法使用断言断言的内容。assertThatExceptionOfType()。我是Junit测试的新手,所以想不出其他的东西。测试catch块接收的异常类型的任何可能方法 方法 public void func() { try { int x = solve(); } catch(Exception1 e) { log.warn(&q

我必须为catch块编写Junit测试。但我无法确定我应该在这里断言什么。由于func()只捕获异常而不抛出任何我无法使用断言断言的内容。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");
    ...
}

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

int solve() throws ExceptionName {
使用此方法将测试放在与类相同的包中,以便可以从测试访问它

更新 最好的方法是更改代码,使其更易于测试,如上所示。 为了不改变代码,您可以使用来自的方式。这可能很棘手。使用Mockito和PowerMockito,您可以控制何时创建
Exception1
Exception2
。基于此,您将知道执行了哪个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);
    }
}

在这里,您不是在调用func方法。您是否将Mockito与JUnit一起使用?正如我在当前示例中所看到的,测试模块使用记录器来记录一些消息。您至少有两个选项:1)以这种方式配置记录器,以便能够捕获和验证记录的消息。2) 使用记录器本身的模拟/存根并验证传递的(消息、异常)元组。@dbl日志将传递事件ID,因此第一个选项不可能。如果有人问我如何模拟记录器,那么我将如何获得异常类型,因为它捕获了多个异常。我无法向您提供更多详细信息,因为我将不得不深入了解它,但这里至少有一个起点-不能仅为了测试目的而更改可见性