Home > Java > javaTutorial > body text

How to Test Methods that Call `System.exit()` in JUnit?

Barbara Streisand
Release: 2024-11-22 10:17:10
Original
658 people have browsed it

How to Test Methods that Call `System.exit()` in JUnit?

How to Test Methods that Call System.exit()?

Issue:

Testing methods that call System.exit() can be challenging as JUnit terminates when System.exit() is invoked.

Solution:

There are several approaches to address this issue:

1. Avoid Using System.exit():

Instead of using System.exit(), consider raising an unchecked exception. This allows JUnit to catch the exception and report test failures without terminating the JVM.

2. Prevent System.exit() from Exiting the JVM:

Employ a security manager that prevents calls to System.exit(). This can be achieved by creating a custom security manager class and modifying the test case to run with it.

3. Use System Rules (JUnit 4.9 ):

Use the ExpectedSystemExit rule to verify that System.exit() is called and test the exit status. This rule provides a convenient way to handle System.exit() in tests.

4. Set System Property (Java 21 ):

To prevent the JVM from terminating due to System.exit(), set the system property -Djava.security.manager=allow.

Code Example Using Security Manager:

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 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);
        super.tearDown();
    }

    public void testExit() throws Exception {
        try {
            System.exit(42);
        } catch (ExitException e) {
            assertEquals("Exit status", 42, e.status);
        }
    }
}
Copy after login

The above is the detailed content of How to Test Methods that Call `System.exit()` in JUnit?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template