Home | Contact Us | FAQ | Search & Site Map | Link to Us
Sign In | Join | Other 45 Sites in Network
HomeAnnouncementsWhite Papers
Discussion GroupsFirst AidDatabasesJavaBeansGUIJava 3DVirtual MachineCORBASecurityToolsGeneral
Java DirectoryOpen Source ProjectsSample Book ChaptersUser GroupsWeb Resources
Related Topics
Databases.NETMore Topics ...

Java Forum / General / July 2005

Tip: Looking for answers? Try searching our database.

java unit test

Thread view: 
Chenxi - 29 Jul 2005 10:10 GMT
hello

i've written a small programme and want to test the main method. the
problem
is that if the parameters are wrong and the programme terminates, JUnit

cannot detect it and the test result would be pass. if i use
System.exit(1),
JUnit cannot catch the termination status and the result will be that
the
test is still running.

How can i let the unit test know whether the programme fails or
succeeds?

==================
public class A{

public A{}

......

public static void main(String[] args){
 if (args.length<2){
   System.out.println("wrong parameters");
   return;
   // System.exit(1);
 }

 ......

}
=================
--
Ingo R. Homann - 29 Jul 2005 10:29 GMT
Hi Chenxi,

> public static void main(String[] args){
>   if (args.length<2){
>     System.out.println("wrong parameters");
>     return;
>     // System.exit(1);
>   }

Do it in a different way:

class X {

  public void main(String[] args) {
    if(args.length!=2) {
      printUsage();
      System.exit(1);
    }
    go(args[0],args[1]);
  }

  public void go(String a, String b) {...}

}

Now, don't test the main-method but test the go-method instead!

Hth,
Ingo
Chenxi - 29 Jul 2005 11:18 GMT
seems to be an alternative way
jan V - 29 Jul 2005 10:31 GMT
> How can i let the unit test know whether the programme fails or
> succeeds?

How about TestCase's fail(String msg) method? No good?
Chenxi - 29 Jul 2005 11:19 GMT
where to put fail(...)?
dont work to me
Thomas Hawtin - 29 Jul 2005 15:22 GMT
> i've written a small programme and want to test the main method. the
> problem
[quoted text clipped - 5 lines]
> the
> test is still running.

Two solutions.

Treat it like a GUI and make the main method really simple. Passing the
logic over to another method and just handling the exit itself.

    public static void main(String[] args) {
        int status = mainImpl(args);
        if (status != 0) {
            System.exit(status);
        }
    }

Use System.setSecurityManager (once). Before System.exit exits, it calls
SecurityManager.checkExit(int status). There you can assert the exit
code and then throw an expected SecurityException. Off the top of my head:

public class ExpectedSecurityException extends SecurityException {
    public ExpectedSecurityException(String message) {
        super(message);
    }
}
public void TestingSecurityManager extends SecurityManager {
    public static TestingSecurityManager install() {
         SecurityManager existing = System.getSecurityManager();
         if (existing instanceof TestingSecurityManager) {
             return (TestingSecurityManager)existing;
         } else if (existing == null) {
             TestingSecurityManager security =
                 new TestingSecurityManager();
             System.setSecurityManager(security);
             return security;
         } else {
             ClassLoader loader = existing.getClass().getClassLoader();
             Assert.fail(
                 "SecurityManager already set "+
                  "<"+existing+">, "+
                  "class: "+existing.getClass()+", "+
                  (loader==null? "bootstap class loader" : (
                          "class loader: <"+loader+"> "+
                          "class loader class: "+loader.getClass()
                  ))
             );
         }
    }
    private Integer exitCode;
    public void reset() {
        exitCode = null;
    }
    public void expectExit(int exitCode) {
        this.exitCode = exitCode;
    }
    @Override
    public void checkPermission(Permission perm) { }
    @Override
    public void checkPermission(Permission perm, Object context) { }
    @Override
    public void checkExit(int status) {
        if (exitCode != null) {
            if (exitCode == status) {
                throw new ExpectedSecurityException(
                    "Pass: Correct status code"
                );
            } else {
                 Assert.assertEqual(
                     "System.exit(int status) wrong code",
                     exitCode.intValue(),
                     status
                 );
            }
        }
    }
}

    private static void assertMainExit(
        int expectedExitCode, String[] args
    ) {
         TestingSecurityManager security =
             TestingSecurityManager.install();
         security.expectExit(exitCode);
         try {
             A.main(args);
             fail("Expected exit, status code: "+exitCode);
         } catch ExpectedSecurityException exc) {
             // Expected.
         } finally {
             security.reset();
         }
    }

The technique is useful embedding third party programs (subject to
copyright).

Tom Hawtin
Signature

Unemployed English Java programmer
http://jroller.com/page/tackline/



Free Magazines

Get these publications absolutely FREE for up to 12 months. There are no hidden fees and no obligation. Simply choose a title, complete the application form and submit it. Read more ...

Oracle MagazineNetwork ComputingComputer WorldBio-IT WorldeWeekInformation WeekInfosecurity
 
Sign In
Join
My Latest Posts
My Monitored Threads
My Blog
My Photo Gallery
My Profile
My Homepage

Start New Thread
Enable EMail Alerts
Rate this Thread



©2008 Advenet LLC   Privacy Policy - Terms of Use
This website includes both content owned or controlled by Advenet as well as content owned or controlled by third parties.