Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a more appropriate to test if the constructor throws an exception?

Tags:

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>(); } 
like image 641
Michael Schnerring Avatar asked Jun 05 '12 15:06

Michael Schnerring


People also ask

What happens if a constructor throws an exception?

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.

Should a constructor throw exceptions?

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.

How do you test when a method throws an exception?

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.

How do you handle exceptions that arise in constructors explain with an example?

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.


1 Answers

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).

like image 90
Dennis Doomen Avatar answered Nov 21 '22 16:11

Dennis Doomen