如何使用 EasyMock 发生异常后立即测试断言?
例如,有一个方法storeIntoFile()
,它检索一个对象并将其写入文件。如果出现异常,该文件将被删除。我希望专门测试此方法,以验证文件在遇到异常时是否被删除。
我有以下测试来执行此操作:
@Test (expected IOException.class)
public void testConnectionFailure throws IOException {
File storeFile = File.createTempFile(
"test",
"test"
);
storeIntoFile(storeFile);
Assert.assertFalse(storeFile.exists());
}
但是在这种情况下,一旦在 storeIntoFile
调用期间遇到异常,测试就会完成,并且不会继续测试以下断言。如何在不使用模拟对象的情况下在异常发生后测试此断言?
最佳答案
这更像是一个 JUnit 问题,而不是 EasyMock。使用 JUnit 4.13,您可以执行以下操作。
public class MyTest {
public interface FileRepository {
void store(File file) throws IOException;
}
private void storeIntoFile(File file) throws IOException {
try {
repository.store(file);
} catch(IOException e) {
file.delete();
throw e;
}
}
private final FileRepository repository = mock(FileRepository.class);
@Test
public void testConnectionFailure() throws IOException {
File storeFile = File.createTempFile("test", "test");
IOException expected = new IOException("the exception");
repository.store(storeFile);
expectLastCall().andThrow(expected);
replay(repository);
IOException actual = assertThrows(IOException.class, () -> storeIntoFile(storeFile));
assertSame(expected, actual);
assertFalse(storeFile.exists());
}
}
我不推荐预期的异常(exception)情况。 assertThrows 更好,因为它允许对异常进行断言。
关于java - 使用 EasyMock 在异常后执行断言,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62139402/