如何为明确抛出的异常编写junit测试

问题描述 投票:0回答:2

我有一个接受String的方法,并检查它是否包含另一个字符串。如果是,那么它将引发一个自定义异常。

Class Test{
    String s2="test";
    public void testex(String s1){
        if(s1.contains(s2))
            throw new customException();
    }
}

我正在为此编写单元测试:

@Test (expected = customException.class){
 when(s1.contains(s2)
                .thenThrow(new customException());
}

但是,我的测试失败,并显示以下错误:java.lang.Exception:Unexpected exception, expected customException but was<org.mockito.exceptions.misusing.MissingMethodInvocationException>

java mockito junit5
2个回答
0
投票

我不太了解您的示例测试。看起来您正在用Mockito嘲笑实际的类,而不是编写junit测试。我会写这样的测试:

使用junit的assertThrows方法:

@Test
void stringContainingThrowsError() {
    Test myClassThatImTesting = new Test();
    assertThrows(CustonException.class, () -> myClassThatImTesting.testex("test"))
}

具有正常的断言:

@Test
void stringContainingThrowsError() {
    Test myClassThatImTesting = new Test();
    try {
        myClassThatImTesting.testex("test");
        fail();
    } catch (Exception ex) {
        assertTrue(ex instanceof CustomException);
    }
}

0
投票

此测试似乎并不是特别有用,但是我相信您的问题是Mockito的when()期望对被模拟对象进行方法调用。

@Test(expcted = CustomException.class)
public void testExMethod() {
    @Mock
    private Test test;
    when(test.testEx()).thenThrow(CustomException.class);
    test.testEx("test string");
}
© www.soinside.com 2019 - 2024. All rights reserved.