stefanbirkner / system-rules

A collection of JUnit rules for testing code which uses java.lang.System.
http://stefanbirkner.github.io/system-rules
Other
546 stars 71 forks source link

Allow assertions after expected System.exit() #5

Closed raphinesse closed 11 years ago

raphinesse commented 11 years ago

Currently this code passes:

@Test
public void failTest() {
    exit.expectSystemExit();
    System.exit(0)
    assertTrue(false);
}

I don't know if this is possible but it would be nice if it would fail instead. This would allow to assert that an appropriate error message was sent to System.err for example.

stefanbirkner commented 11 years ago

At the moment I only know one solution for your problem. You have to write an own rule for the assertion and use RuleChain in order to get its finished method executed after the ExpectedSystemExit rule. Here is an example:

public class Exiter {
    String message = "";

    public void doExit() {
        message = "call exit";
        System.exit(0);
    }
}

public class ExiterTest {
    public ExpectedSystemExit exit = ExpectedSystemExit.none();
    public CheckMessage checkMessage = new CheckMessage();

    @Rule
    public TestRule allRules = RuleChain.outerRule(checkMessage).around(exit);

    @Test
    public void writesMessage() {
        exit.expectSystemExit();
        Exiter exiter = new Exiter();
        checkMessage.exiter = exiter;
        exiter.doExit();
    }

    private static final class CheckMessage extends TestWatcher {
        Exiter exiter;

        @Override
        protected void finished(Description description) {
            assertEquals("call exit", exiter.message);
        }
    }
}
raphinesse commented 11 years ago

Thank you for your quick response. I'll give it a try when I find some time to continue working on that particular project.

raphinesse commented 11 years ago

Nice one :+1: