• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

How to test the void method having System.exit(-1) in Junit

 
Deepa Rajesh
Greenhorn
Posts: 6
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I have a Standalone program which has a void method and will exit if any validation fails.If i give the input which will fail in validation , Test case has stopped and it is not continuing to the next case.


Please help to write the proper test case for this situation.( I am very new to JUNIT)
 
Greg Charles
Sheriff
Posts: 2993
12
Firefox Browser IntelliJ IDE Java Mac Ruby
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Some sort of mocking framework might help, but here's something that would work with pure JUnit:

  • In your class, defne a protected exit() method that just calls System.exit(-1)
  • Change all other calls to System.exit(-1) to use exit() instead.
  • In your JUnit test, override your class, and redefine exit() to throw a runtime exception instead of calling System.exit(-1)
  • Now in your tests you can catch the exception and put assertions in the catch block depending on whether you expected an exit or not



  •  
    Junilu Lacar
    Bartender
    Pie
    Posts: 7749
    60
    Android Eclipse IDE IntelliJ IDE Java Linux Mac Scala Spring Ubuntu
    • Likes 1
    • Mark post as helpful
    • send pies
    • Quote
    • Report post to moderator
    I have used an approach similar to what Greg suggested. Extending the class under test (CUT) and overriding one or more methods works really nicely, assuming the CUT is not declared as final. However, throwing an exception is expensive and increases test execution time slightly. Since unit tests should run as fast as possible, I'd prefer to avoid throwing an exception outside of the actual CUT if I can help it. I would just add a boolean field in the extended class and set it to true in the redefined exit() method. No need to add a getter, just access the boolean field directly from the test case.

     
    Greg Charles
    Sheriff
    Posts: 2993
    12
    Firefox Browser IntelliJ IDE Java Mac Ruby
    • Mark post as helpful
    • send pies
    • Quote
    • Report post to moderator
    Very nice! That is a better way to do it.
     
    Jeanne Boyarsky
    author & internet detective
    Marshal
    Posts: 34973
    378
    Eclipse IDE Java VI Editor
    • Mark post as helpful
    • send pies
    • Quote
    • Report post to moderator
    As an alternative to the approaches described above, you could write a mockable helper class:



    This gives you a nice class with an interface that you can mock out normally.
     
    • Post Reply
    • Bookmark Topic Watch Topic
    • New Topic