Reputation: 11801
I have a unit test like this, using
org.junit.contrib.java.lang.system.ExpectedSystemExit
org.junit.rules.TemporaryFolder
@Rule
public TemporaryFolder folder = new TemporaryFolder();
@Rule
public final ExpectedSystemExit exit = ExpectedSystemExit.none();
@Test
public void createsFile_integrationTest() throws Exception{
final File tempFolder = folder.newFolder("temp");
exit.expectSystemExitWithStatus(0);
exit.checkAssertionAfterwards(new Assertion() {
@Override
public void checkAssertion() throws Exception {
assertTrue(new File(tempFolder.getAbsolutePath() + "/created-file.txt").exists());
}
main.run(tempFolder.getAbsolutePath() +"/created-file.txt");
});
The problem with this, is that the temporary folder starts tearing down as soon as it gets system exit, and not after my checkAssertion()
is called.
Is there a way I can prevent my temporary folder tear down until the end of checkAssertion?
Edit: I think what the answer is - is to do a refactor and separate these to two tests - one where I test system exit, and the other where I test file creation.
Upvotes: 1
Views: 3727
Reputation: 24510
You have to enforce an order on the rules so that the ExpectedSystemExit
rule can check the assertion before TemporaryFolder
is shutdown. You can use JUnit's RuleChain for this.
private final TemporaryFolder folder = new TemporaryFolder();
private final ExpectedSystemExit exit = ExpectedSystemExit.none();
@Rule
public TestRule chain = RuleChain.outerRule(folder).around(exit);
@Test
public void createsFile_integrationTest() throws Exception {
final File tempFolder = folder.newFolder("temp");
exit.expectSystemExitWithStatus(0);
exit.checkAssertionAfterwards(new Assertion() {
@Override
public void checkAssertion() throws Exception {
assertTrue(new File(tempFolder.getAbsolutePath() + "/created-file.txt").exists());
}
});
main.run(tempFolder.getAbsolutePath() +"/created-file.txt");
}
Upvotes: 1