java.lang.NullPointerException for static button in JavaFX with static reference - java

Okay so I have a bit a conundrum. I have a Qaurtz Cron that I want to use to schedule and run some Java Tests. These task are scheduled through a gui that Uses JavaFX. However, the job itself calls a run tests method. The job forces me to make certain elements static, but by making them static, I get a null pointer exception. I would really appreciate some help here.
So here is the job class that forces things to be static.
public class newJob implements Job{
public void execute(JobExecutionContext arg0) throws JobExecutionException {
System.out.println("We are attempting the job now");
try {
FXMLDocumentController.runScheduledTests();
} catch (Throwable e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
Inside my controller I have something like this:
public static void runTests() throws SQLException, IOException {
// Set running to true. In current form we do not use this bool,
// however, we may
// make changes that rely on this.
running = true;
FileOutputStream fos = null;
// Verify that users exist, and there is a url with the word max in it
int count = DBHelpers.getResults("SELECT * FROM USERS;", new String[] { "ID" }).length();
// Verify that we have both users and a maximo url to work with.
if ((!userList.isEmpty() || count > 0) && userMaxListChoice.length() > 5) {
// Set the proper driver, default to chrome if none is selected
if (IEbutton.isSelected()) {
BrowserConfig.setDriver(Browsers.IE());
} else {
BrowserConfig.setDriver(Browsers.Chrome());
}
// Let's assign maximo. If no one has clicked the use UserList
// button, assume that the data inside
// maximo name is good to use
if (userMaxListChoice != null) {
BrowserConfig.setMaximo(userMaxListChoice);
// System.out.println("used maxLIst choice");
} else {
// If the user has not selected a name from the maximo list,
// let's grab whatever
// they have entered in the maximoName field.
BrowserConfig.setMaximo(maximoName.getText());
}
// Set the system pause based on the interval string
int pause = Integer.parseInt(interval.getText().toString());
// Make sure the puase is in miliseconds
pause = pause * 1000;
BrowserConfig.setInterval(pause);
Note that the runScheduledTests() methods does some configuring and calls the runTest method. Inside the run test method is where I'm hitting the error specifically this line:
if (IEbutton.isSelected()) {
BrowserConfig.setDriver(Browsers.IE());
} else {
BrowserConfig.setDriver(Browsers.Chrome());
}
The reason is that above I have this :
#FXML
public static RadioButton ChromeButton;
#FXML
public static RadioButton IEbutton;
As I said this is a bit of an issue, If I don't make them static the job class yells at me for making a non-static reference.
How can I resolve this conflict?

TL;DR : You shouldn't use static on the fields annotated with #FXML.
For more information go through - javafx 8 compatibility issues - FXML static fields
You could load the FXML by using the FXMLLoader and then get an instance of the controller from it. By doing this, you can convert the method runScheduledTests() into a non-static method.
public class newJob implements Job{
public void execute(JobExecutionContext arg0) throws JobExecutionException {
try {
FXMLLoader fxmlLoader =
new FXMLLoader(getClass().getResource("path-to-fxml.fxml"));
fxmlLoader.load();
FXMLDocumentController fxmlDocumentController =
(FXMLDocumentController)fxmlLoader.getController();
fxmlDocumentController.runScheduledTests(); // convert the method to non-static
} catch (Throwable e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}

The problem is you are trying to use static when the controller itself is not static. Take into consideration I recommend taking a look at the difference between static and non-static here. In regards to fixing your code. First make your buttons ChromeButton and IEbutton not static. Then when your application class, something like this:
public class HelloWorld extends Application {
public static void main(String[] args) {
launch(args);
}
#Override
public void start(Stage primaryStage) {
//pass a reference of your stage to job.
}
}
Then Pass a reference of your buttons or controller into the Job class as a variable. Like this:
public class newJob implements Job{
private RadioButton chrome;
private RadioButton ie;
public newJob(RadioButton chrome, RadioButton ie) {
this.chrome = chrome;
this.ie = ie;
}
public void execute(JobExecutionContext arg0) throws JobExecutionException {
System.out.println("We are attempting the job now");
try {
FXMLDocumentController.runScheduledTests();
} catch (Throwable e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
The core of your problem is controller variables CANNOT be static as the controller is dependent on instantiating the class and passing the required information in. The best way to fix this is by passing a reference either to the buttons or the class by using variables in the constructor. Please read the link I sent you to get a better understanding between static and non-static. Also, if you are confused about constructors take a look here as well.

Related

java.lang.NoSuchMethodException error but method does exist

I know there is, like, over 5 questions that ask this but mine is different. I am trying to get all classes in a package and run the tick function. Here is what one of my classes look like:
package com.stupidrepo.mydirectory.yayay;
public class test {
public void tick(MinecraftClient client) {
System.out.println(client.player.getName());
}
}
Here is how I am attempting to call this function:
ScanResult scanResult = new ClassGraph().acceptPackages("com.stupidrepo.mydirectory.yayay").enableClassInfo().scan();
private void doIt(MinecraftClient client) {
scanResult.getAllClasses().forEach((classInfo -> {
// System.out.println(classInfo.getName());
try {
classInfo.loadClass().getMethod("tick", MinecraftClient.class).invoke(null, client);
} catch (Exception e) {
e.printStackTrace();
}
}));
}
When I call the doIt function, it keeps giving me the java.lang.NoSuchMethodException error. When I print classInfo.getMethods();, it shows me [public void com.stupidrepo.mydirectory.yayay.test.tick(net.minecraft.client.MinecraftClient)].
So the method is there but java says it isn't. Please help! (By the way the code is for a Fabric MC mod)
The method tick is not static. But, when you are invoking method, you are not giving instance (but null), so it try to run the method as static. Such as It's not static, it failed.
To fix it, you can:
Set your method as static, for example:
package com.stupidrepo.mydirectory.yayay;
public class test {
public static void tick(MinecraftClient client) {
System.out.println(client.player.getName());
}
}
Create a new instance like that:
try {
Class<?> clzz = classInfo.loadClass(); // get class
Object obj = clzz.getConstructor().newInstance(); // create instance
clzz.getMethod("tick", MinecraftClient.class).invoke(obj, client); // get and call method
} catch (Exception e) {
e.printStackTrace();
}

How to prevent object from getting garbage collected

I have a utility class which starts a long running background thread. The utility class is initialized in main class. But utility class object is getting garbage collected. How can i prevent that. Here is my class structure.
public class Main {
public static void main(String[] args) throws Exception {
Utility u = new Utility();
u.startTask(); //This is not referenced after this and hence getting gc'ed
.....
....
api.addMessageCreateListener(event -> {
/////continuously running
}
}
}
What i want is to prevent Utility object from getting garbage collected.
I assume the Method Utility#startTask() starts Threads on its own, otherwise this would be a blocking call and the main-Method would not end before startTask returned.
However this should not stop you from implementing the Runnable Interface in Utility itself. As long as the Utility runs in its own Thread, you do not need to worry about the enclosing method returning. Since the Tread is still running, the Instance will not be collected.
public class Threading {
public static void main(String[] args) {
Utility utility = new Threading().new Utility();
Future utilFuture = Executors.newSingleThreadExecutor().submit(utility);
System.out.println("end main");
}
public class Utility implements Runnable {
#Override
public void run() {
System.out.println("Start Utility");
for(int i = 0; i < 10; i++) {
try {
Thread.sleep(1000);
System.out.println("foo: " + i);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
}
}
}
}
}
Note: In your case you might not need the Future, but it is an extremely useful tool to interrupt the Execution if needed.

Android thread sometimes doesn't start

So I'm having problems with my threads in an Android project. I have a ThreadStarter class, with a BuildScreen() function, which actually creates the layout for each activity. The only problem is, sometimes the threads just won't start, and I have no idea why. They work like 98% of the time though, but when they don't, the current activity will never get initalized, and the user has to restart the app, which is inconvenient.
Here is a snippet of my code:
public class ThreadStarter
{
public static void BuildScreen()
{
try
{
GlobalVariables.screenDrawer.onStart();
GlobalVariables.listInitaliser.onStart();
Logger.log("ThreadStarter.BuildScreen", "Threads started");
}
catch(IllegalThreadStateException e)
{
GlobalVariables.screenDrawer.StopThread();
GlobalVariables.listInitaliser.StopThread();
Logger.log("ThreadStarter.BuildScreen", "Threads stopped");
GlobalVariables.screenDrawer.onStart();
GlobalVariables.listInitaliser.onStart();
}
catch(Exception e)
{
Logger.Error("Couldn't stop or start the threads!");
Logger.Error("Exception () Message: " + e.getMessage());
}
}
}
The threads:
public class ListInitialiser extends Thread
{
private static ListInitialiser _thread;
public synchronized void run()
{
GlobalVariables.CurrentActivity.UpdateLists();
}
public void onStart()
{
_thread = new ListInitialiser();
_thread.start();
}
public void StopThread()
{
if (_thread != null)
{
_thread.interrupt();
_thread = null;
}
}
}
I won't insert the ScreenDrawer thread here, because it's pretty much the same, except it calls another function.
And this is how every activity is created (of course the contentView differs in each file):
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
getWindow().getAttributes().windowAnimations = R.style.Fade;
setContentView(R.layout.activity_fine_data_3);
GlobalVariables.CurrentActivity = this;
ThreadStarter.BuildScreen();
Logger.log("INFORMATION", "Person3DataActivity (Information 3/5)");
}
In the GlobalVariables section I have these variables:
public static ScreenDrawer screenDrawer = new ScreenDrawer();
public static ListInitialiser listInitaliser = new ListInitialiser();
If anyone has a solution or and idea, please share it with me.
Thanks in advance.
EDIT: Okay, so I took onof's (rather harsh but useful :)) advice, and refactored my code to use AsyncTask instead. It seems to be working pretty fine. I managed to implement it into my AbstractActivity class, which is the parent of every Activity I use, and now all I have to do is call BuildScreen() method in every onCreate method.
Thanks for the replies everyone.
try to add this to your class where u declared Global Variables
private static ListInitialiser instance;
public static synchronized ListInitialiser getInstance() {
if (instance == null)
instance = new ListInitialiser();
return instance;
}
Everytime you donot have to create new when u r taking static.I dont know but may be this can help
You can't rely on static variables as everything that is static (non final) in Android can be cleared any time the system need memory. So don't think static = storage.
You should instead instantiate the objects when you need them, like following:
public static ScreenDrawer getScreenDrawer() {
return new ScreenDrawer();
}
public static ListInitialiser getListInitialiser () {
return new ListInitialiser ();
}

Constructor and method not working as expected in Java program

Constructor and method not working as expected in Java program
I have the following code:
package principal;
public class Principal {
public static void main(String[] args) {
Thread filosofos[]=new Thread[5];
for (int i=0;i<5;i++) {
System.out.println("loop");
filosofos[i]=new Thread();
filosofos[i].start();
}
// TODO Auto-generated method stub
}
}
package principal;
public class Filosofo implements Runnable{
static final int tamanho=5;
static int talheres[]=new int[tamanho];
static Semaforo semaforo= new Semaforo(1);
static int quantidade=0;
int id;
public Filosofo(){
System.out.println("Construtor iniciado.");
for (int i=0;i<tamanho;i++) {
talheres[i]=0;
}
quantidade++;
id=quantidade;
}
public void run () {
System.out.println("Filosofo "+id+" iniciado");
try {
// Filosofo pensando
Thread.sleep(1000);
} catch (Exception e) {
}
semaforo.down();
System.out.println("Filosofo "+id+" comendo");
semaforo.up();
}
}
The program should exhibit the string "Construtor iniciado." and the other 2 strings of method run. However when I run the code nothing happens only output that I receive is
loop
loop
loop
loop
loop
why the string of the constructor is not showing up? Why the method run is not running as expected? It looks like the constructor and the method run are not running at all, and I don't know what is going wrong.
You have declared class Filosofo but you never create a single instance of it.
Perhaps you want to pass a new instance of Filosofo as thread constructor parameter for each thread?
package principal;
public class Principal
{
public static void main(String[] args)
{
Thread filosofos[]=new Thread[5];
for (int i=0;i<5;i++) {
filosofos[i]=new Thread(new Filosofo());
filosofos[i].start();
}
}
}
Except this, instead of using a static field for counting Filosofo instances and assign them an id, why you don't just pass the id in the constructor?
Also the other fields, don't need to be static, pass the shared fields, like semaforo, in the constructor and copy them in a class field.
I don't know the meaning of talheres field and I don't understand why you reinitialize a static field in each instance constructor, maybe you can just initialize once in main and pass that field in the constructor of each Filosofo, as you know, arrays are not copied, only a reference to them is copied.
Also instead of catch (Exception e) you should use catch (InterruptedException e).
You should do something useful with the exception, like printing it.
If you intend to ignore an exception at least you should add a very detailed comment on why you are doing that.
You never instantiate any Filosofo, just Threads.

Java: How to test methods that call System.exit()?

I've got a few methods that should call System.exit() on certain inputs. Unfortunately, testing these cases causes JUnit to terminate! Putting the method calls in a new Thread doesn't seem to help, since System.exit() terminates the JVM, not just the current thread. Are there any common patterns for dealing with this? For example, can I subsitute a stub for System.exit()?
[EDIT] The class in question is actually a command-line tool which I'm attempting to test inside JUnit. Maybe JUnit is simply not the right tool for the job? Suggestions for complementary regression testing tools are welcome (preferably something that integrates well with JUnit and EclEmma).
Indeed, Derkeiler.com suggests:
Why System.exit() ?
Instead of terminating with System.exit(whateverValue), why not throw an unchecked exception? In normal use it will drift all the way out to the JVM's last-ditch catcher and shut your script down (unless you decide to catch it somewhere along the way, which might be useful someday).
In the JUnit scenario it will be caught by the JUnit framework, which will report that
such-and-such test failed and move smoothly along to the next.
Prevent System.exit() to actually exit the JVM:
Try modifying the TestCase to run with a security manager that prevents calling System.exit, then catch the SecurityException.
public class NoExitTestCase extends TestCase
{
protected static class ExitException extends SecurityException
{
public final int status;
public ExitException(int status)
{
super("There is no escape!");
this.status = status;
}
}
private static class NoExitSecurityManager extends SecurityManager
{
#Override
public void checkPermission(Permission perm)
{
// allow anything.
}
#Override
public void checkPermission(Permission perm, Object context)
{
// allow anything.
}
#Override
public void checkExit(int status)
{
super.checkExit(status);
throw new ExitException(status);
}
}
#Override
protected void setUp() throws Exception
{
super.setUp();
System.setSecurityManager(new NoExitSecurityManager());
}
#Override
protected void tearDown() throws Exception
{
System.setSecurityManager(null); // or save and restore original
super.tearDown();
}
public void testNoExit() throws Exception
{
System.out.println("Printing works");
}
public void testExit() throws Exception
{
try
{
System.exit(42);
} catch (ExitException e)
{
assertEquals("Exit status", 42, e.status);
}
}
}
Update December 2012:
Will proposes in the comments using System Rules, a collection of JUnit(4.9+) rules for testing code which uses java.lang.System.
This was initially mentioned by Stefan Birkner in his answer in December 2011.
System.exit(…)
Use the ExpectedSystemExit rule to verify that System.exit(…) is called.
You could verify the exit status, too.
For instance:
public void MyTest {
#Rule
public final ExpectedSystemExit exit = ExpectedSystemExit.none();
#Test
public void noSystemExit() {
//passes
}
#Test
public void systemExitWithArbitraryStatusCode() {
exit.expectSystemExit();
System.exit(0);
}
#Test
public void systemExitWithSelectedStatusCode0() {
exit.expectSystemExitWithStatus(0);
System.exit(0);
}
}
The library System Lambda has a method catchSystemExit.With this rule you are able to test code, that calls System.exit(...):
public class MyTest {
#Test
public void systemExitWithArbitraryStatusCode() {
SystemLambda.catchSystemExit(() -> {
//the code under test, which calls System.exit(...);
});
}
#Test
public void systemExitWithSelectedStatusCode0() {
int status = SystemLambda.catchSystemExit(() -> {
//the code under test, which calls System.exit(0);
});
assertEquals(0, status);
}
}
For Java 5 to 7 the library System Rules has a JUnit rule called ExpectedSystemExit. With this rule you are able to test code, that calls System.exit(...):
public class MyTest {
#Rule
public final ExpectedSystemExit exit = ExpectedSystemExit.none();
#Test
public void systemExitWithArbitraryStatusCode() {
exit.expectSystemExit();
//the code under test, which calls System.exit(...);
}
#Test
public void systemExitWithSelectedStatusCode0() {
exit.expectSystemExitWithStatus(0);
//the code under test, which calls System.exit(0);
}
}
Full disclosure: I'm the author of both libraries.
How about injecting an "ExitManager" into this Methods:
public interface ExitManager {
void exit(int exitCode);
}
public class ExitManagerImpl implements ExitManager {
public void exit(int exitCode) {
System.exit(exitCode);
}
}
public class ExitManagerMock implements ExitManager {
public bool exitWasCalled;
public int exitCode;
public void exit(int exitCode) {
exitWasCalled = true;
this.exitCode = exitCode;
}
}
public class MethodsCallExit {
public void CallsExit(ExitManager exitManager) {
// whatever
if (foo) {
exitManager.exit(42);
}
// whatever
}
}
The production code uses the ExitManagerImpl and the test code uses ExitManagerMock and can check if exit() was called and with which exit code.
You actually can mock or stub out the System.exit method, in a JUnit test.
For example, using JMockit you could write (there are other ways as well):
#Test
public void mockSystemExit(#Mocked("exit") System mockSystem)
{
// Called by code under test:
System.exit(); // will not exit the program
}
EDIT: Alternative test (using latest JMockit API) which does not allow any code to run after a call to System.exit(n):
#Test(expected = EOFException.class)
public void checkingForSystemExitWhileNotAllowingCodeToContinueToRun() {
new Expectations(System.class) {{ System.exit(anyInt); result = new EOFException(); }};
// From the code under test:
System.exit(1);
System.out.println("This will never run (and not exit either)");
}
One trick we used in our code base was to have the call to System.exit() be encapsulated in a Runnable impl, which the method in question used by default. To unit test, we set a different mock Runnable. Something like this:
private static final Runnable DEFAULT_ACTION = new Runnable(){
public void run(){
System.exit(0);
}
};
public void foo(){
this.foo(DEFAULT_ACTION);
}
/* package-visible only for unit testing */
void foo(Runnable action){
// ...some stuff...
action.run();
}
...and the JUnit test method...
public void testFoo(){
final AtomicBoolean actionWasCalled = new AtomicBoolean(false);
fooObject.foo(new Runnable(){
public void run(){
actionWasCalled.set(true);
}
});
assertTrue(actionWasCalled.get());
}
I like some of the answers already given but I wanted to demonstrate a different technique that is often useful when getting legacy code under test. Given code like:
public class Foo {
public void bar(int i) {
if (i < 0) {
System.exit(i);
}
}
}
You can do a safe refactoring to create a method that wraps the System.exit call:
public class Foo {
public void bar(int i) {
if (i < 0) {
exit(i);
}
}
void exit(int i) {
System.exit(i);
}
}
Then you can create a fake for your test that overrides exit:
public class TestFoo extends TestCase {
public void testShouldExitWithNegativeNumbers() {
TestFoo foo = new TestFoo();
foo.bar(-1);
assertTrue(foo.exitCalled);
assertEquals(-1, foo.exitValue);
}
private class TestFoo extends Foo {
boolean exitCalled;
int exitValue;
void exit(int i) {
exitCalled = true;
exitValue = i;
}
}
This is a generic technique for substituting behavior for test cases, and I use it all the time when refactoring legacy code. It not usually where I'm going to leave thing, but an intermediate step to get the existing code under test.
For VonC's answer to run on JUnit 4, I've modified the code as follows
protected static class ExitException extends SecurityException {
private static final long serialVersionUID = -1982617086752946683L;
public final int status;
public ExitException(int status) {
super("There is no escape!");
this.status = status;
}
}
private static class NoExitSecurityManager extends SecurityManager {
#Override
public void checkPermission(Permission perm) {
// allow anything.
}
#Override
public void checkPermission(Permission perm, Object context) {
// allow anything.
}
#Override
public void checkExit(int status) {
super.checkExit(status);
throw new ExitException(status);
}
}
private SecurityManager securityManager;
#Before
public void setUp() {
securityManager = System.getSecurityManager();
System.setSecurityManager(new NoExitSecurityManager());
}
#After
public void tearDown() {
System.setSecurityManager(securityManager);
}
Create a mock-able class that wraps System.exit()
I agree with EricSchaefer. But if you use a good mocking framework like Mockito a simple concrete class is enough, no need for an interface and two implementations.
Stopping test execution on System.exit()
Problem:
// do thing1
if(someCondition) {
System.exit(1);
}
// do thing2
System.exit(0)
A mocked Sytem.exit() will not terminate execution. This is bad if you want to test that thing2 is not executed.
Solution:
You should refactor this code as suggested by martin:
// do thing1
if(someCondition) {
return 1;
}
// do thing2
return 0;
And do System.exit(status) in the calling function. This forces you to have all your System.exit()s in one place in or near main(). This is cleaner than calling System.exit() deep inside your logic.
Code
Wrapper:
public class SystemExit {
public void exit(int status) {
System.exit(status);
}
}
Main:
public class Main {
private final SystemExit systemExit;
Main(SystemExit systemExit) {
this.systemExit = systemExit;
}
public static void main(String[] args) {
SystemExit aSystemExit = new SystemExit();
Main main = new Main(aSystemExit);
main.executeAndExit(args);
}
void executeAndExit(String[] args) {
int status = execute(args);
systemExit.exit(status);
}
private int execute(String[] args) {
System.out.println("First argument:");
if (args.length == 0) {
return 1;
}
System.out.println(args[0]);
return 0;
}
}
Test:
public class MainTest {
private Main main;
private SystemExit systemExit;
#Before
public void setUp() {
systemExit = mock(SystemExit.class);
main = new Main(systemExit);
}
#Test
public void executeCallsSystemExit() {
String[] emptyArgs = {};
// test
main.executeAndExit(emptyArgs);
verify(systemExit).exit(1);
}
}
System Stubs - https://github.com/webcompere/system-stubs - is also able to solve this problem. It shares System Lambda's syntax for wrapping around code that we know will execute System.exit, but that can lead to odd effects when other code unexpectedly exits.
Via the JUnit 5 plugin, we can provide insurance that any exit will be converted to an exception:
#ExtendWith(SystemStubsExtension.class)
class SystemExitUseCase {
// the presence of this in the test means System.exit becomes an exception
#SystemStub
private SystemExit systemExit;
#Test
void doSomethingThatAccidentallyCallsSystemExit() {
// this test would have stopped the JVM, now it ends in `AbortExecutionException`
// System.exit(1);
}
#Test
void canCatchSystemExit() {
assertThatThrownBy(() -> System.exit(1))
.isInstanceOf(AbortExecutionException.class);
assertThat(systemExit.getExitCode()).isEqualTo(1);
}
}
Alternatively, the assertion-like static method can also be used:
assertThat(catchSystemExit(() -> {
//the code under test
System.exit(123);
})).isEqualTo(123);
A quick look at the api, shows that System.exit can throw an exception esp. if a securitymanager forbids the shutdown of the vm. Maybe a solution would be to install such a manager.
You can use the java SecurityManager to prevent the current thread from shutting down the Java VM. The following code should do what you want:
SecurityManager securityManager = new SecurityManager() {
public void checkPermission(Permission permission) {
if ("exitVM".equals(permission.getName())) {
throw new SecurityException("System.exit attempted and blocked.");
}
}
};
System.setSecurityManager(securityManager);
You can test System.exit(..) with replacing Runtime instance.
E.g. with TestNG + Mockito:
public class ConsoleTest {
/** Original runtime. */
private Runtime originalRuntime;
/** Mocked runtime. */
private Runtime spyRuntime;
#BeforeMethod
public void setUp() {
originalRuntime = Runtime.getRuntime();
spyRuntime = spy(originalRuntime);
// Replace original runtime with a spy (via reflection).
Utils.setField(Runtime.class, "currentRuntime", spyRuntime);
}
#AfterMethod
public void tearDown() {
// Recover original runtime.
Utils.setField(Runtime.class, "currentRuntime", originalRuntime);
}
#Test
public void testSystemExit() {
// Or anything you want as an answer.
doNothing().when(spyRuntime).exit(anyInt());
System.exit(1);
verify(spyRuntime).exit(1);
}
}
There are environments where the returned exit code is used by the calling program (such as ERRORLEVEL in MS Batch). We have tests around the main methods that do this in our code, and our approach has been to use a similar SecurityManager override as used in other tests here.
Last night I put together a small JAR using Junit #Rule annotations to hide the security manager code, as well as add expectations based on the expected return code. http://code.google.com/p/junitsystemrules/
Most solutions will
terminate the test (method, not the entire run) the moment System.exit() is called
ignore an already installed SecurityManager
Sometimes be quite specific to a test framework
restrict to be used at max once per test case
Thus, most solutions are not suited for situations where:
Verification of side-effects are to be performed after the call to System.exit()
An existing security manager is part of the testing.
A different test framework is used.
You want to have multiple verifications in a single test case. This may be strictly not recommended, but can be very convenient at times, especially in combination with assertAll(), for example.
I was not happy with the restrictions imposed by the existing solutions presented in the other answers, and thus came up with something on my own.
The following class provides a method assertExits(int expectedStatus, Executable executable) which asserts that System.exit() is called with a specified status value, and the test can continue after it. It works the same way as JUnit 5 assertThrows. It also respects an existing security manager.
There is one remaining problem: When the code under test installs a new security manager which completely replaces the security manager set by the test. All other SecurityManager-based solutions known to me suffer the same problem.
import java.security.Permission;
import static java.lang.System.getSecurityManager;
import static java.lang.System.setSecurityManager;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.fail;
public enum ExitAssertions {
;
public static <E extends Throwable> void assertExits(final int expectedStatus, final ThrowingExecutable<E> executable) throws E {
final SecurityManager originalSecurityManager = getSecurityManager();
setSecurityManager(new SecurityManager() {
#Override
public void checkPermission(final Permission perm) {
if (originalSecurityManager != null)
originalSecurityManager.checkPermission(perm);
}
#Override
public void checkPermission(final Permission perm, final Object context) {
if (originalSecurityManager != null)
originalSecurityManager.checkPermission(perm, context);
}
#Override
public void checkExit(final int status) {
super.checkExit(status);
throw new ExitException(status);
}
});
try {
executable.run();
fail("Expected System.exit(" + expectedStatus + ") to be called, but it wasn't called.");
} catch (final ExitException e) {
assertEquals(expectedStatus, e.status, "Wrong System.exit() status.");
} finally {
setSecurityManager(originalSecurityManager);
}
}
public interface ThrowingExecutable<E extends Throwable> {
void run() throws E;
}
private static class ExitException extends SecurityException {
final int status;
private ExitException(final int status) {
this.status = status;
}
}
}
You can use the class like this:
#Test
void example() {
assertExits(0, () -> System.exit(0)); // succeeds
assertExits(1, () -> System.exit(1)); // succeeds
assertExits(2, () -> System.exit(1)); // fails
}
The code can easily be ported to JUnit 4, TestNG, or any other framework, if necessary. The only framework-specific element is failing the test. This can easily be changed to something framework-independent (other than a Junit 4 Rule
There is room for improvement, for example, overloading assertExits() with customizable messages.
Use Runtime.exec(String command) to start JVM in a separate process.
There is a minor problem with the SecurityManager solution. Some methods, such as JFrame.exitOnClose, also call SecurityManager.checkExit. In my application, I didn't want that call to fail, so I used
Class[] stack = getClassContext();
if (stack[1] != JFrame.class && !okToExit) throw new ExitException();
super.checkExit(status);
A generally useful approach that can be used for unit and integration testing, is to have a package private (default access) mockable runner class that provides run() and exit() methods. These methods can be overridden by Mock or Fake test classes in the test modules.
The test class (JUnit or other) provides exceptions that the exit() method can throw in place of System.exit().
package mainmocked;
class MainRunner {
void run(final String[] args) {
new MainMocked().run(args);
}
void exit(final int status) {
System.exit(status);
}
}
the class with main() below, also has an altMain() to receive the mock or fake runner, when unit or integration testing:
package mainmocked;
public class MainMocked {
private static MainRunner runner = new MainRunner();
static void altMain(final String[] args, final MainRunner inRunner) {
runner = inRunner;
main(args);
}
public static void main(String[] args) {
try {
runner.run(args);
} catch (Throwable ex) {
// Log("error: ", ex);
runner.exit(1);
}
runner.exit(0);
} // main
public void run(String[] args) {
// do things ...
}
} // class
A simple mock (with Mockito) would be:
#Test
public void testAltMain() {
String[] args0 = {};
MainRunner mockRunner = mock(MainRunner.class);
MainMocked.altMain(args0, mockRunner);
verify(mockRunner).run(args0);
verify(mockRunner).exit(0);
}
A more complex test class would use a Fake, in which run() could do anything, and an Exception class to replace System.exit():
private class FakeRunnerRuns extends MainRunner {
#Override
void run(String[] args){
new MainMocked().run(args);
}
#Override
void exit(final int status) {
if (status == 0) {
throw new MyMockExitExceptionOK("exit(0) success");
}
else {
throw new MyMockExitExceptionFail("Unexpected Exception");
} // ok
} // exit
} // class
Another technique here is to introduce additional code into the (hopefully small number of) places where the logic does the System.exit(). This additional code then avoids doing the System.exit() when the logic is being called as part of unit test. For example, define a package private constant like TEST_MODE which is normally false. Then have the unit test code set this true and add logic to the code under test to check for that case and bypass the System.exit call and instead throw an exception that the unit test logic can catch. By the way, in 2021 and using something like spotbugs, this problem can manifest itself in the obscure error that "java.io.IOException: An existing connection was forcibly closed by the remote host".
Calling System.exit() is a bad practice, unless it's done inside a main(). These methods should be throwing an exception which, ultimately, is caught by your main(), who then calls System.exit with the appropriate code.

Categories