简体   繁体   中英

How to allow testing helper method to throw exception without catching it in calling methods?

I am writing tests, using testNG in this case, and I want to write my own assert method which uses some reflection to assert something is true. I intend to use the method all over in other helper methods.

There are checked exceptions that the test can throw, but shouldn't if done right. In all cases if the assert method throws an exception my desire is for it to propagate all the way to the top of the stack, causing the test to fail with a stack trace.

However, I would prefer not to have to add a throws method to every one of my test classes. Especially since there may be causes were other methods throw the same exception that I want eclipse to remind me to check for. Is there a way I can tell the testing framework itself that a specific exception being thrown should fail the test with a stack trace, as if I had thrown it through the entire stack?

I could use org.testing.Assert.fail , but that only allows me to provide a string instead of a full stack trace. I could wrap the checked exception in a RuntimeException , but I feel that makes it (slightly) harder for testers to understand what actually happened. Is there a more direct way to say "fail here due to this exception" ?

I see a signature in testNG taking an actual exception:

http://testng.org/javadoc/org/testng/Assert.html#fail(java.lang.String,%20java.lang.Throwable)

And also fail throws a runtime exception ( TestNGException ), so you can launch that exception yourself and the test harness will understand.

Use java.lang.AssertionError to fail a test; that's what fail() uses internally. You can extend this error to add custom data which you need.

I also don't think that throws Exception is an anti-pattern in unit tests. There is a lot of code which (for whatever reasons) throws checked exceptions. It doesn't add much information to a test when you declare exactly which exceptions it can throw ( unlike normal methods).

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