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.
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.
You can use Assert. ThrowsException<T> and Assert.
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.
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.
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.
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.
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.
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.
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 ) ); } }
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() );
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