简体   繁体   中英

Showing (unexpected) exception messages in JUnit tests (Netbeans)

When a JUnit test receives an unexpected RuntimeException, the NetBeans Test Results tab shows the name of the test that failed, followed by a stack trace.

Ex.

someFailedTest caused an ERROR: at (stack trace lines start here)

Not as helpful as it could be.

While the stack trace does let us track down where a problem occurred, it would be nice if NB also showed any message that accompanied the exception. (Ex. "x must be > 0 but was -2", or whatever.)

As far as I can tell it doesn't seem to be making the details available. Is there a way to show exception details that I'm missing?

I could use a try/catch or an error log, but is there a better way?

Here's an example of a (fake) "test" which shows a message clearly in Eclipse, but not in NB. Any insight welcome... yes I know this isn't an exception but it's the same type of problem.

    @Test
    public void testTest() {

        String file = "test";
        File f = new File("../" + file);
        if (!f.exists()) {
            Assert.fail("File was not found at " + file);
        }
    }

Edit... Yep, little bit confused now - I've seen it work correctly at least once or twice, but I'm unable to reproduce it now. I'll have to see if I can reproduce somewhere I can post screenshots from later...

Edit #2... Found some stranger behavior. If I do this (which is going to be my workaround for today), the test result list still looks the same, but I DO get a nice red and very helpful error message in the console:

String msg = "FXML file was not found at " + file;
System.err.print("test");
Assert.fail(msg);

But if I comment out the System.err line entirely, I get nothing in the console. Even more bizarre, if I put an empty string, I still get nothing in the console at all (Well, maybe print() is smart enough to ignore the empty string..):

String msg = "FXML file was not found at " + file;
System.err.print("");
Assert.fail(msg);

I know it's not what you want to hear, but I believe the standard way to do what you want is to use the try-catch like this:

try{
    ....
}catch(Throwable t){
    //Add some code to print the details of the Throwable here
    fail(t.getMessage());
}

I'm not aware of any settings that would allow you to tell Netbeans/JUnit to display the message of an uncaught exception/throwable.

My Netbeans shows the message. Here's an example:

带消息的junit示例

Maybe Netbeans doesn't show the message under some circumstances. Maybe your top-level exception doesn't have a message associated with it. I'm using Netbeans 8.1, and I've made no relevant configuration changes.

Here's the example you posted. The message is also visible here.

第二个带有消息的junit示例

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