Normally you test, if an exception gets thrown in a certain method, as follows. I use FluentAssertions:
[Fact] public void Exception_gets_thrown() { // Arrange var foo = new Foo("validArgument"); // Act/Assert foo.Invoking(f => f.Bar(null)) // null is an invalid argument .ShouldThrow<ArgumentNullException>(); }
But how to test, if an exception gets thrown in the constructor? I just did it like this, but is there maybe a more appropriate way via FluentAssertions?
[Fact] public void Constructor_throws_Exception() { // Arrange Action a = () => new Foo(null); // null is an invalid argument // Act/Assert a.ShouldThrow<ArgumentNullException>(); }
When throwing an exception in a constructor, the memory for the object itself has already been allocated by the time the constructor is called. So, the compiler will automatically deallocate the memory occupied by the object after the exception is thrown.
Yes, constructors are allowed to throw an exception in Java. A Constructor is a special type of a method that is used to initialize the object and it is used to create an object of a class using the new keyword, where an object is also known as an Instance of a class.
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.
You would catch the exception in the calling code, not in the constructor. Exceptions aren't returned in the same way as return values, they skip up the stack to the first appropriate catch block, so whilst you can't return a value from the constructor you can throw an exception from it.
That's exactly how you're supposed to test for exceptions and that's what ShouldThrow<T>()
and ShouldNotThrow<T>()
were designed for in the first place. In fact, the Invoking()
approach might be marked as obsolete in the next big version (2.0.0).
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