1

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.

Stefan Birkner
  • 24,059
  • 12
  • 57
  • 72
dwjohnston
  • 11,163
  • 32
  • 99
  • 194
  • What happens if you switch the order of `expectSystemExitWithStatus()` and `checkAssertionAfterwards()`? I'm not sure what `checkAssertionAfterwards()` does, but from what you are doing here it seems to only register a callback. Do you know when this callback is actually executed? – Code-Apprentice Jan 20 '17 at 04:14
  • @Code-Apprentice - I did try that - it doesn't work either. – dwjohnston Jan 20 '17 at 04:14

1 Answers1

1

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"); 

}
Stefan Birkner
  • 24,059
  • 12
  • 57
  • 72