wood burning stoves*
The moose likes Beginning Java and the fly likes Testing main() / Hiding static method Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Testing main() / Hiding static method" Watch "Testing main() / Hiding static method" New topic
Author

Testing main() / Hiding static method

Chad Schultz
Greenhorn

Joined: Mar 25, 2007
Posts: 23
My task is simple. I want my JUnit tests to test the main() method. The tricky part is that when there is an error that prevents the problem from continuing, it exits- naturally.

Luckily, the program is already designed to call a method that then exits- so for testing purposes, I thought I would create a subclass in the test case file that overrides that method with one that throws a RuntimeException instead of calling System.exit(). However, I'm having trouble.

This is a basic representation of the program:


The test file goes something like this:



BTW, yes, I have read the JavaRanch page on overriding vs hiding. Unfortunately, that doesn't seem to have helped. Every time I run the test, it never completes; when I debug, I find that it reaches the original class's System.exit() instead of the new method. I've tried passing in a stub class in ABC's application context file (both casting it as ABC or as ABCStub). I've tried putting ABCStub in a separate file. I've tried making ABCStub not a static class. I've been banging my head against the wall for hours and still haven't found a solution to this simple problem: hiding that static exit() method.
Ernest Friedman-Hill
author and iconoclast
Marshal

Joined: Jul 08, 2003
Posts: 24183
    
  34

You can't. "Hiding" means that code compiled to use ABCTest will see ABCTest's exit method, but code compiled to use ABC's -- like ABC itself -- will continue to use ABC's, even if you call ABCTest.main(). That's just how it works. You're expecting some kind of polymorphism, but there isn't any -- that's the whole issue.

One solution: make ABC.exit() an instance method that calls. Make main() invoke exit() on a static protected member variable which holds an ABC by default. Then in ABCTest, override exit() and then set that member to hold an ABCTest.

There are other ways to do it, but they're all going to hinge on making exit() an instance method.


[Jess in Action][AskingGoodQuestions]
 
It is sorta covered in the JavaRanch Style Guide.
 
subject: Testing main() / Hiding static method
 
Similar Threads
Threads
Exceptions (long one) Your response requested.
app doesn't exit because of JOptionPane
Source code file, multiple class definitions
Want to know what Throws does?