org.junit.rules.TestRule
public class ExpectedSystemExit
extends java.lang.Object
implements org.junit.rules.TestRule
ExpectedSystemExit
allows in-test specification of expected
System.exit(...)
calls.
If your code calls System.exit(),
then your test stops and doesn't
finish. The ExpectedSystemExit
rule allows in-test specification of
expected System.exit()
calls. Furthermore you cannot use JUnit's
assert methods because of the abnormal termination of your code. As a
substitute you can provide an Assertion
object to the
ExpectedSystemExit
rule.
Some care must be taken if your system under test creates a new thread and
this thread calls System.exit()
. In this case you have to ensure that
the test does not finish before System.exit()
is called.
public class AppWithExit { public static String message; public static int doSomethingAndExit() { message = "exit ..."; System.exit(1); } public static int doNothing() { } }
public void AppWithExitTest { @Rule public final ExpectedSystemExit exit = ExpectedSystemExit.none(); @Test public void exits() { exit.expectSystemExit(); AppWithExit.doSomethingAndExit(); } @Test public void exitsWithStatusCode1() { exit.expectSystemExitWithStatus(1); AppWithExit.doSomethingAndExit(); } @Test public void writesMessage() { exit.checkAssertionAfterwards(new Assertion() { public void checkAssertion() { assertEquals("exit ...", AppWithExit.message); } }); AppWithExit.doSomethingAndExit(); } @Test public void systemExitWithStatusCode1() { exit.expectSystemExitWithStatus(1); AppWithExit.doSomethingAndExit(); } @Test public void noSystemExit() { AppWithExit.doNothing(); //passes } }
Modifier and Type | Method | Description |
---|---|---|
org.junit.runners.model.Statement |
apply(org.junit.runners.model.Statement base,
org.junit.runner.Description description) |
|
void |
checkAssertionAfterwards(Assertion assertion) |
|
void |
expectSystemExit() |
|
void |
expectSystemExitWithStatus(int status) |
|
static ExpectedSystemExit |
none() |
public static ExpectedSystemExit none()
public void expectSystemExitWithStatus(int status)
public void expectSystemExit()
public void checkAssertionAfterwards(Assertion assertion)
public org.junit.runners.model.Statement apply(org.junit.runners.model.Statement base, org.junit.runner.Description description)
apply
in interface org.junit.rules.TestRule
Copyright © 2011–2018. All rights reserved.