简体   繁体   中英

Using the try catch statement to print out statements

@Test
public void test() throws Exception
{
    try
    {
         //some code over here
    }
    catch(Exception e)
    {
        if(e.toString() == null)
        {
               System.out.print("Test Case: Successful");
        }
        else
        {
               System.out.println("Test Case: Failed");
               System.out.println("Failing Reason: "+ e.toString());
        }
    }
}

Currently I have the above code. However, when executing the JUnit. Nothing was printed into the console.

Did I do anything wrong? Or is it that i cannot use System.out.println in JUnit.

So I have a second question: Is it possible to print out the total amount of time taken to complete the JUnit test?

This code doesn't make sense.

  • If no exception is thrown, no exception is thrown, so you won't end up in the catch block; so there isn't a way you'd end up there in the "successful" case (unless you're testing explicitly for throwing an exception whose getMessage() returns null , which is... hmm; and in that case you should have a fail() as the last line of the try )
  • JUnit already handles failures for you. If your approach were the "right" way to do it, you'd have to put this code in every test case. What a lot of repeated code.
  • If the code in the try block fails by throwing an Exception , you catch and swallow the problem. Sure, it gets printed to the console, but JUnit has no means of capturing that, so it looks like the test passes. (It will still fail properly if an Error or other Throwable is thrown).

In short: just get rid of your try / catch block, leaving the code in the try , and let the testing framework do exactly what it is designed for.

Code in the catch block will only run if the code in the try block throws an exception. As you have it coded, it is not going to print anything out unless an exception is throw. This is likely what you meant:

@Test
public void test() throws Exception
{
    try
    {
         //some code over here

         // last line of try block
         System.out.print("Test Case: Successful"); 
    }
    catch(Exception e)
    {
        System.out.println("Test Case: Failed");
        System.out.println("Failing Reason: "+ e.toString());
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM