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/

相关文章:

java - ConstraintViolationException 处理程序未在 Micronaut 中执行

java - 当 Spring 请求过滤器中加载对象时,Hibernate session 将关闭

java - Android 库 zip

java - 我怎样才能模拟 bean 返回它自己的参数?

AngularJS 测试 w/jasmine 和 $httpBackend

c++ - 如何修改 C++ runtime_error 的 what 字符串?

java - 为什么我们不需要在 C# 中声明 serialVersionUID(或等效的)?

testing - 什么是冒烟测试?

php - 有没有办法让PDO异常被默认捕获?

rest - 自定义 Spring Boot 异常处理以防止在 Rest 响应中返回 Stacktraces