我有一个 JUnit 测试,我正在测试一个带有空参数的方法。如果参数/arguments 为 null,那么我将抛出 NullPointerException。该方法本身只会抛出 IOException。我在类的模拟对象上使用 doThrow,但在我看来,我正在丢失 doThrow() 构造中的异常,我无法捕获它。此外,我绝对不想在我的单元测试中使用 try catch。所以我同样使用@Rules。这是代码片段:
public class TableTest {
@Rule
public ExpectedException exception = ExpectedException.none();
private static Table spyTable;
@Test
public void testCreateTableWithNullTableName_throwsIOEXception() throws IOException {
final String tableName = null;
mockConfig = mock(Configuration.class);
spyPersonTable = spy(new PersonTable());
doThrow(new IllegalArgumentException()).when(spyPersonTable).createTable(tableName, mockConfig);
// exception.expect(IllegalArgumentException.class);
}
使用@rule 的异常对象,如果我使用注释行来捕获我的异常,在 doThrow() 构造中创建的异常将丢失并且我无法捕获它。我的单元测试将失败并提示:
Expected test to throw an instance of java.lang.IllegalArgumentException
如果我对该行进行注释,则测试工作正常。这是我尝试测试的方法的样子:
public void createTable(final String tableName, final Configuration config) throws IOException
该方法需要抛出 IOException,因为在创建表期间抛出的特定异常是 IOException 的子类。
对于这种类型的检查异常,我在 JUnit 测试中捕获异常是否错误。
最佳答案
您似乎想测试该方法是否抛出异常;但是通过使用 doThrow().when(sut).createTable(...)
,您可以阻止 SUT 的正常行为。
只是做:
final PersonTable table = new PersonTable();
table.createTable(null, null); // theoretically throws IllegalArgumentException
然后检查是否有抛出的异常。不知道你是如何用你的 @Rule
做到这一点的,但我不使用它,这里我将如何做到这一点:
final PersonTable table = new PersonTable();
try {
table.createTable(null, null);
fail("No exception thrown!");
} catch (IllegalArgumentException e) {
assertEquals(e.getMessage(), "the expected message");
}
关于java - 在 doThrow JUNIT 之后捕获异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22497349/