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

Java 如何为显式抛出的异常编写junit测试,java,mockito,junit5,Java,Mockito,Junit5,我有一个接收字符串的方法,并检查它是否包含另一个字符串。如果是,则抛出一个自定义异常 Class Test{ String s2="test"; public void testex(String s1){ if(s1.contains(s2)) throw new customException(); } } 我正试图为此编写一个单元测试: @Test (expected = customException.class){ w

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

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:
意外异常,预期customException,但它是

我没有完全理解您的示例测试。看起来您是在用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);
    }
}

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

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

你为什么要嘲笑你想测试的东西?我无法理解这个例子。另外,Java中的类型总是在
PascalCase
->
CustomException
中。此外,问题被标记为junit5,但@Test注释似乎来自JUnit4。这使我更加困惑。