1+ package com .baeldung .system .exit ;
2+
3+ import static org .junit .Assert .assertEquals ;
4+
5+ import java .security .Permission ;
6+
7+ import org .junit .After ;
8+ import org .junit .Before ;
9+ import org .junit .Test ;
10+
11+ public class SystemExitUnitTest {
12+
13+ protected static class ExitException extends SecurityException {
14+
15+ private static final long serialVersionUID = 1L ;
16+ public final int status ;
17+
18+ public ExitException (int status ) {
19+ this .status = status ;
20+ }
21+ }
22+
23+ private static class NoExitSecurityManager extends SecurityManager {
24+ @ Override
25+ public void checkPermission (Permission perm ) {
26+ }
27+
28+ @ Override
29+ public void checkPermission (Permission perm , Object context ) {
30+ }
31+
32+ @ Override
33+ public void checkExit (int status ) {
34+ super .checkExit (status );
35+ throw new ExitException (status );
36+ }
37+ }
38+
39+ private SecurityManager securityManager ;
40+
41+ private SystemExitExample example ;
42+
43+ @ Before
44+ public void setUp () throws Exception {
45+ example = new SystemExitExample ();
46+ securityManager = System .getSecurityManager ();
47+ System .setSecurityManager (new NoExitSecurityManager ());
48+ }
49+
50+ @ After
51+ public void tearDown () throws Exception {
52+ System .setSecurityManager (securityManager );
53+ }
54+
55+ @ Test
56+ public void testExit () throws Exception {
57+ try {
58+ example .readFile ();
59+ } catch (ExitException e ) {
60+ assertEquals ("Exit status" , 2 , e .status );
61+ }
62+ }
63+ }
0 commit comments