Update:  removed my mock object from the new test for clarity.

I have reevaluated my approach to how to write a test to catch exceptions.  NUnit has an attribute for ExpectedException which I have been using to test exceptions in my code.  I ran across an instance of a specialized Exception the other day, that had custom parameters as part of the exception.  Using the ExpectedException attribute, I was able to test that the Exception was thrown, but not the custom parameters that were part of the Exception. For example of an Exception with custom parameters, check out the framework MembershipCreateUserException.

 

Here is the setup code to put the tests in context.

 

        DynamicMock mockService;

        IAuthenticationContract agent;

        CustomMembershipProvider provider;

 

 

        [SetUp]

        public void Setup()

        {

            mockService = new DynamicMock(typeof(IAuthenticationContract));

            agent = (IAuthenticationContract)mockService.MockInstance;

            provider = new CustomMembershipProvider(agent);

 

        }

 

My original Test looked as follows:

 

        [Test]

        [ExpectedException(typeof(MembershipCreateUserException))]

        public void ValidateUserReturnsFalseWithBlankPassword()

        {

 

            mockService.ExpectNoCall(“ValidateCredentials”);

 

            provider.ValidateUser(“Someone”, “”);

            mockService.Verify();

 

        }

 

What I am expecting is that the provider.ValidateUser() call will throw the exception.  This does work as expected, but at this point I only get that a type of MembershipCreateUserException was called. I cannot inspect any properties of the exception at this point, but the test passes.

 

Here is my new test:

 

        [Test]

        public void ValidateUserReturnsFalseWithBlankPassword()

        {

 

            try

            {

                provider.ValidateUser(“Someone”, “”);

                Assert.Fail(“The Blank Password should have thrown an Error”);

 

            }

            catch (MembershipCreateUserException ex)

            {

                Assert.AreEqual(MembershipCreateStatus.InvalidPassword, ex.StatusCode);

            }

 

 

        }

 

Notice that my intent is also to just ensure the the provider.ValidateUser() call is going to fail.  I am catching this exception that is expected and validating the Exception status.  This last test more explicitly states my intent of the test.

 

Technorati Tags: , ,
Advertisements