Friday 1 May 2020

junit: How to test System.exit

‘system-rules’ api is used to test system.exit.

<dependency>
         <groupId>com.github.stefanbirkner</groupId>
         <artifactId>system-rules</artifactId>
         <version>1.19.0</version>
         <scope>test</scope>
</dependency>

Follow below steps to test system exit codes.

Step 1: Create a rule of type ExpectedSystemExit.

@Rule
public final ExpectedSystemExit exit = ExpectedSystemExit.none();

Step 2: Use 'expectSystemExitWithStatus' method to test system exit with status code.
exit.expectSystemExitWithStatus(0);

Find the below working application.

App.java
package com.sample.app;

public class App {

 public void exitApp() {
  System.exit(0);
 }

}

AppTest.java

package com.sample.app;

import org.junit.Rule;
import org.junit.Test;
import org.junit.contrib.java.lang.system.ExpectedSystemExit;

public class AppTest {

 @Rule
 public final ExpectedSystemExit exit = ExpectedSystemExit.none();

 @Test
 public void exitApp() {
  exit.expectSystemExitWithStatus(0);

  App app = new App();

  app.exitApp();
 }
}



You may like

No comments:

Post a Comment