Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best way to test exceptions with Assert to ensure they will be thrown

Do you think that this is a good way for testing exceptions? Any suggestions?

Exception exception = null; try{     //I m sure that an exeption will happen here } catch (Exception ex){     exception = ex; }  Assert.IsNotNull(exception); 

I'm using MS Test.

like image 688
Hannoun Yassir Avatar asked Apr 12 '09 00:04

Hannoun Yassir


People also ask

How do you assert if an exception is thrown?

When using JUnit 4, we can simply use the expected attribute of the @Test annotation to declare that we expect an exception to be thrown anywhere in the annotated test method. In this example, we've declared that we're expecting our test code to result in a NullPointerException.

Which assert method is used to validate that a method throws a particular exception or not?

You can use Assert. ThrowsException<T> and Assert.

Should JUnit tests throw exceptions?

The JUnit TestRunners will catch the thrown Exception regardless so you don't have to worry about your entire test suite bailing out if an Exception is thrown. This is the best answer.

How do you handle exceptions in test cases?

Create a java class file named TestRunner. java in C:\>JUNIT_WORKSPACE to execute test case(s). Compile the MessageUtil, Test case and Test Runner classes using javac. Now run the Test Runner, which will run the test cases defined in the provided Test Case class.

How to assert there is an exception in a test?

This implementation provides a way of asserting there is an exception using the syntax below. I prefer this style since all the actions and assertions are now within the body of the test. [TestMethod]publicvoidAddWithNegativeNumberThrowsException(){// ArrangeStringCalculatorsc=newStringCalculator();// Act => AssertExceptionAssert. Throws(()=>sc.

What does assert throws<t> do?

A neat feature of Assert.Throws<T> is that it actually returns the exception that was thrown within the passed Action. Let's say we want our current ArgumentOutOfRangeException 's to throw with the exception message: "The input kilometersPerHour must be greater than or equal to zero." We'll need to modify our tests to account for this.

How do you pass a test without throwing an exception?

If the test runner completes the test without throwing an exception or failing an Assert, the test passes. Next, we provide the type argument, which needs to be a type of Exception, the type of exception we expect our code to throw, ArgumentOutOfRangeException.

How does assert fail work in unit testing?

In all unit testing frameworks I am familiar with, Assert.Fail works by throwing an exception, so the generic catch will actually mask the failure of the test. If SomethingThatCausesAnException () does not throw, the Assert.Fail will, but that will never bubble out to the test runner to indicate failure.


2 Answers

I have a couple of different patterns that I use. I use the ExpectedException attribute most of the time when an exception is expected. This suffices for most cases, however, there are some cases when this is not sufficient. The exception may not be catchable - since it's thrown by a method that is invoked by reflection - or perhaps I just want to check that other conditions hold, say a transaction is rolled back or some value has still been set. In these cases I wrap it in a try/catch block that expects the exact exception, does an Assert.Fail if the code succeeds and also catches generic exceptions to make sure that a different exception is not thrown.

First case:

[TestMethod] [ExpectedException(typeof(ArgumentNullException))] public void MethodTest() {      var obj = new ClassRequiringNonNullParameter( null ); } 

Second case:

[TestMethod] public void MethodTest() {     try     {         var obj = new ClassRequiringNonNullParameter( null );         Assert.Fail("An exception should have been thrown");     }     catch (ArgumentNullException ae)     {         Assert.AreEqual( "Parameter cannot be null or empty.", ae.Message );     }     catch (Exception e)     {         Assert.Fail(              string.Format( "Unexpected exception of type {0} caught: {1}",                             e.GetType(), e.Message )         );     } } 
like image 178
tvanfosson Avatar answered Sep 28 '22 01:09

tvanfosson


Now, 2017, you can do it easier with the new MSTest V2 Framework:

Assert.ThrowsException<Exception>(() => myClass.MyMethodWithError());  //async version await Assert.ThrowsExceptionAsync<SomeException>(   () => myObject.SomeMethodAsync() ); 
like image 28
Icaro Bombonato Avatar answered Sep 28 '22 01:09

Icaro Bombonato