java - 使用 EasyMock 在异常后执行断言

标签 java testing exception assert easymock

如何使用 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/

相关文章:

testing - Google Play 服务测试

android - 如何对蓝牙配件进行单元测试?

java - 如何在不中断 for 循环的情况下抛出异常?

java - 使用 Unsafe 时未报告的异常

Java 8 内部包含列表的对象组列表

PHP mysqli 测试运行

java - 为什么我会收到 gson 异常 : Expecting object found?

exception - 捕获 SAPSQL_DATA_LOSS

java - 在大型未排序列表中查找 n 个最大值,一次仅处理一页值

java - Android Dropbox API - 如何从 SharedPreferences 检索身份验证 key