如何为显式抛出的异常编写 junit 测试

How to write junit test for exceptions which are explicitly thrown

我有一个接受字符串的方法,并检查它是否包含另一个字符串。如果是,则抛出自定义异常。

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>

我不太了解您的示例测试。看起来您是在用 Mockito 模拟实际的 class 而不是编写 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);
    }
}

这个测试似乎不是特别有用,但我相信你的问题是 Mockito 的 when() 需要一个模拟对象的方法调用。

@Test(expcted = CustomException.class)
public void testExMethod() {
    @Mock
    private Test test;
    when(test.testEx()).thenThrow(CustomException.class);
    test.testEx("test string");
}