Can I test whether a particular Exception is not thrown?
The other way round is easy using #Test[expect=MyException].
But how can I negate this?
If you want to test if a particular Exception is not thrown in a condition where other exceptions could be thrown, try this:
try {
myMethod();
}
catch (ExceptionNotToThrow entt){
fail("WHOOPS! Threw ExceptionNotToThrow" + entt.toString);
}
catch (Throwable t){
//do nothing since other exceptions are OK
}
assertTrue(somethingElse);
//done!
You can do the following using assertj
if you want to check if exception is not thrown then
Throwable throwable = catchThrowable(() -> sut.method());
assertThat(throwable).isNull();
or you expect to throw
Throwable throwable = catchThrowable(() -> sut.method());
assertThat(throwable).isInstanceOf(ClassOfExecption.class)
.hasMessageContaining("expected message");
catch-exception makes the example of Freiheit a bit more concise:
catchException(a).myMethod();
assertFalse(caughtException() instanceof ExceptionNotToThrow);
Another latest solution could be using Junit5 assertDoesNotThrow:
assertDoesNotThrow( () -> myMethod() , "MyException is not thrown")
Use #Test(expected = Test.None::class) (in Kotlin)
Related
I'm a beginner of AssertJ. I encountered some issue when I use AssertJ to do Unit Testing.
JAVA: version 8
AssertJ: 3.11.1
I have a source code as below, to capture an exception and throw another exception.
try {
Integer.valueOf(valueA);
} catch(Exception e) {
throw new XXXException("value is not valid", e);
}
My test case as below failed, and I was told wrong exception assert, it's a bit confusing.
Throwable thrown = catchThrowable(() -> {
contract.init(ctx, "A", "100A", "B", "200");
});
assertThat(thrown).isInstanceOf(XXXException.class);
The error message as below, it seems like the original exception was captured by AssertJ. Anyone can help? Is it a bug or my mistake of AssertJ API usage? Many Thanks.
java.lang.AssertionError:
Expecting:
<java.util.IllegalFormatConversionException: d != java.lang.String>
to be an instance of:
<xxxx.XXXException>
but was:
<"java.util.IllegalFormatConversionException: d != java.lang.String
Here's my attempt to reproduce the issue, the test passes as expected:
#Test
public void test() {
Throwable thrown = catchThrowable(() -> f());
assertThat(thrown).isInstanceOf(RuntimeException.class);
}
private void f() {
try {
Integer.valueOf("100A");
} catch (Exception e) {
throw new RuntimeException("value is not valid", e);
}
}
Can you show us what contract.init is doing?
Another possibility would be in the stack trace, if it contains a %d somewhere stack trace it might be interpreted by a String.format but hard to say without more details.
I have this scenario in which some tests can throw different exceptions.
#Test
public void addDevice(){
device.addDevice(); // this may throw exception 1
device.verifyStatus("Ready");
device.open(); // this may throw exception 2
device.verifyStatus("Open");
}
#Test
public void otherTest(){
device.act(); // this may throw exception 3
device.verifyStatus("Ready");
}
#After
public void tearDown(){
// handle the exception here
}
I want to handle those exceptions in the #After section without wrapping the test with try, catch.
Is that possible?
No, it is not possible.
You could wrap the test anyway with a try-catch-block. Then you could store the exception to a member variable instead of handling it.
In the #After method you can check whether the exception is null or not.
Due to your comment that you have hundreds of tests with this code I assume that this is set up logic which should actually be in an #Before method.
Thus, you could specify an external resource rule with a before and after method: https://github.com/junit-team/junit/wiki/Rules#externalresource-rules
In the before() method you perform the set up, catch and store the exceptions and in the after() method you handle them.
But does it make sense to handle the exception later? Can you run your test cases successfully if the set up fails?
I have a method that throws exception. And i have a test like this.
#Rule
public ExpectedException expectedEx = ExpectedException.none();
#Test
public void shouldThrowExceptionIfValidationFails() throws Exception {
doThrow(new InvalidException("Invalid Token")).when(obj).foo(any());
expectedEx.expect(InvalidException.class);
expectedEx.expectMessage("Invalid Token");
// my method call
// verify DB save doesn't happens
assertTrue(false);
}
The test assert for exception, and since the exception is thrown the test passes. It doesn't care about the last line assertTrue(false)
How can i make sure that my other assertions are also satisfied.
This is the pattern I follow for this case. It uses ExpectedException as designed. I like the throw e rather than failing after method method call in the try because it will not result in a false-positive if someone decides to delete the fail (which people have a tendency to do when they see fail() or if a test is failing because it hits a fail()).
#Test
public void shouldThrowExceptionIfValidationFails() throws Exception {
doThrow(new InvalidException("Invalid Token")).when(obj).foo(any());
expectedEx.expect(InvalidException.class);
expectedEx.expectMessage("Invalid Token");
try{
// my method call
}catch(InvalidException e){
// verify DB save doesn't happens
assertTrue(false);
throw e;
}
}
I'm using ScalaTest for testing some Scala code.
I currently testing for expected exceptions with code like this
import org.scalatest._
import org.scalatest.matchers.ShouldMatchers
class ImageComparisonTest extends FeatureSpec with ShouldMatchers{
feature("A test can throw an exception") {
scenario("when an exception is throw this is expected"){
evaluating { throw new Exception("message") } should produce [Exception]
}
}
}
But I would like to add additional check on the exception, e.g. I would like to check that the exceptions message contains a certain String.
Is there a 'clean' way to do this? Or do I have to use a try catch block?
I found a solution
val exception = intercept[SomeException]{ ... code that throws SomeException ... }
// you can add more assertions based on exception here
You can do the same sort of thing with the evaluating ... should produce syntax, because like intercept, it returns the caught exception:
val exception =
evaluating { throw new Exception("message") } should produce [Exception]
Then inspect the exception.
If you need to further inspect an expected exception, you can capture it using this syntax:
val thrown = the [SomeException] thrownBy { /* Code that throws SomeException */ }
This expression returns the caught exception so that you can inspect it further:
thrown.getMessage should equal ("Some message")
you can also capture and inspect an expected exception in one statement, like this:
the [SomeException] thrownBy {
// Code that throws SomeException
} should have message "Some message"
I have an if condition which checks for value and the it throws new NumberFormatException
Is there any other way to code this
if (foo)
{
throw new NumberFormatException
}
// ..
catch (NumberFormatException exc)
{
// some msg...
}
If you are doing something such as this:
try
{
// some stuff
if (foo)
{
throw new NumberFormatException();
}
}
catch (NumberFormatException exc)
{
do something;
}
Then sure, you could avoid the exception completely and do the 'do something' part inside the conditional block.
If your aim is to avoid to throw a new exception:
if(foo)
{
//some msg...
} else
{
//do something else
}
Don't throw exceptions if you can handle them in another, more elegant manner. Exceptions are expensive and should only be used for cases where there is something going on beyond your control (e.g. a database server is not responding).
If you are trying to ensure that a value is set, and formatted correctly, you should try to handle failure of these conditions in a more graceful manner. For example...
if(myObject.value != null && Checkformat(myObject.Value)
{
// good to go
}
else
{
// not a good place to be. Prompt the user rather than raise an exception?
}
In Java, you can try parsing a string with regular expressions before trying to convert it to a number.
If you're trying to catch your own exception (why???) you could do this:
try { if (foo) throw new NumberFormatException(); }
catch(NumberFormatexception) {/* ... */}
if you are trying to replace the throwing of an exception with some other error handling mechanism your only option is to return or set an error code - the problem is that you then have to go and ensure it is checked elsewhere.
the exception is best.
If you know the flow that will cause you to throw a NumberFormatException, code to handle that case. You shouldn't use Exception hierarchies as a program flow mechanism.