Search code examples
mstest

Can MSTest ignore the nested exceptions and only test against the last?


Imagine that you have a function that checks if the provided string value is empty like below:

string IsNotEmpty(string value)
{
    if (!string.IsEmpty(value)) return value
    else throw new Exception("Value is empty");
}

Also imagine that we have many other parts of our code that call this generic function to check if there is a value and if not throw a more specific exception than the generic one. As an example i will provide the below code:

string CheckEmail(string email)
{
    try
    {
        return IsNotEmpty(email);
    }
    catch(Exception ex)
    {
        throw new **EmptyEmailException**("Please provide your email");
    }
}

Now i want to write a MSTest for the CheckEmail function that expects an exception of type EmptyEmailException to be thrown. But unfortunately the test captures only the generic Exception from IsNotEmpty function, it stops execution and the code never tests the second exception.

Things i have done without any success:

  1. I wrote my test with ExpectedException attribute.
  2. I wrote my test with Assert.ThrowsException.
  3. I updated the exception settings in VS to not brake on exceptions of type Exception, just to see if that will resolve my issue.

No matter what i do MSTest always reports the first exception and of course my test fails. Below is my current test code:

[TestMethod]
public void When_Validating_SignInRequest_And_Email_IsEmpty_Raise_EmptyEmailException()
{
    var ex = Assert.ThrowsException<EmptyEmailException>(
                () => CheckEmail(string.Empty)
            );
}

Can anyone point me to the right direction?

Thanks.


Solution

  • This works fine on my end:

    using Microsoft.VisualStudio.TestTools.UnitTesting;
    using System;
    
    namespace MyNamespace
    {
        public class EmptyEmailException : Exception
        {
            public EmptyEmailException(string message) : base(message)
            { }
        }
    
        public class MyClass
        {
            public static string IsNotEmpty(string value)
            {
                if (!string.IsNullOrEmpty(value))
                    return value;
                else
                    throw new Exception("Value is empty");
            }
    
            public static string CheckEmail(string email)
            {
                try
                {
                    return IsNotEmpty(email);
                }
                catch
                {
                    throw new EmptyEmailException("Please provide your email");
                }
            }
        }
    
        [TestClass]
        public class UnitTest1
        {
            [TestMethod]
            public void TestMethod1()
            {
                Assert.ThrowsException<EmptyEmailException>(() => MyClass.CheckEmail(string.Empty));
            }
        }
    }