使用EasyMock在异常后执行断言

问题描述 投票:0回答:1

如何在EasyMock发生异常后立即测试断言?例如,有一种方法storeIntoFile()可以检索对象并将其写入文件。如果出现异常,将删除该文件。我正在尝试测试此方法,以验证文件是否在遇到异常时被删除。我要进行以下测试:

@Test (expected IOException.class)
public void testConnectionFailure throws IOException {
File storeFile = File.createTempFile(
        "test",
        "test"
    );
storeIntoFile(storeFile);
Assert.assertFalse(storeFile.exists());
}

但是,在这种情况下,只要在storeIntoFile调用期间遇到异常,测试就会立即完成,并且不会继续测试以下断言。如何在异常后不使用模拟对象的情况下测试此断言?

java testing exception assert easymock
1个回答
0
投票

[EasyMock不仅仅是一个JUnit问题。使用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());
    }
}

我不建议预期的例外。 assertThrows更好,因为它允许对异常进行断言。

© www.soinside.com 2019 - 2024. All rights reserved.