For example, if I had the following class that I want to test:
public class SomeClass{
public void someMethod() {
try {
//Some code, where comething could go wrong
} catch (Exception err) {
//Handling it amounts to logging the problem and trying to continue
}
}
}
If I then test this method with JUnit, then if something does go wrong in the try clause and the catch code is run, then the test will pass.
I want to make it so that the test will fail if the catch clause instructions are run.
I did think of a few ways I could try and write tests so that I get an equivalent sort of functionality, but there are reasons for each one that I do not want to approach it that way. It seems like trying to fail the test if any catch clause is reached is the cleanest way to do this, if that is in fact possible
Notes:
I know I could verify certain features of the code and check if they are a certain value/have been run a number of times with Mockito. However I want a solution where if changes were made to the test method that radically altered how it worked (but not what task was essentially being carried out) then I won't have to rewrite the test.
Unfortunately, just to make this proble more difficult, I am unable to make any modifictions to the source code. This position is out of my control so I have to work within these confines.
EDIT:
SomeClass is the class that I wish to test. It is not the actual JUnit test. I have edited my original question to try and clarify this.
You can just let take JUnit to take care of the Exception by adding it to your method sig: public void someTest() throws Exception. However if you want to catch the Exception yourself to assert it being caugt the example you have given is good to go.
In your unit test case, you can use a try-catch block. Let me show you what I mean. You use the try block to execute the code under test. If the method throws an exception, that will be covered by the catch block.
Assertions assertThrows() APIThe assertThrows() method asserts that execution of the supplied executable block or lambda expression throws an exception of the expectedType . It is an overloaded method and takes the following parameters. expectedType – Test code is expected to throw an exception of this type.
In order to test the exception thrown by any method in JUnit 4, you need to use @Test(expected=IllegalArgumentException. class) annotation. You can replace IllegalArgumentException. class with any other exception e.g. NullPointerException.
I've had to deal with this sort of problem before. I ended up mocking the logging sub-system (not simple but not overly complex) and listened for the 'interesting' logging calls, and then flagging failures when it happened.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With