Assert exception from NUnit to MS TEST

后端 未结 3 1159
终归单人心
终归单人心 2021-01-04 05:10

I have some tests where i am checking for parameter name in exception. How do i write this in MS TEST?

ArgumentNullExc         


        
相关标签:
3条回答
  • 2021-01-04 05:56
    public static class ExceptionAssert
    {
      public static T Throws<T>(Action action) where T : Exception
      {
        try
        {
          action();
        }
        catch (T ex)
        {
          return ex;
        }
    
        Assert.Fail("Expected exception of type {0}.", typeof(T));
    
        return null;
      }
    }
    

    You can use the extension method above as a test helper. Here is an example of how to use it:

    // test method
    var exception = ExceptionAssert.Throws<ArgumentNullException>(
                  () => organizations.GetOrganization());
    Assert.AreEqual("lawbaseFixedContactRepository", exception.ParamName);
    
    0 讨论(0)
  • 2021-01-04 05:59

    Shameless plug, but I wrote a simple assembly that makes asserting exceptions and exception messages a little easier and more readable in MSTest using Assert.Throws() syntax in the style of nUnit/xUnit.

    You can download the package from Nuget using: PM> Install-Package MSTestExtensions

    Or you can see the full source code here: https://github.com/bbraithwaite/MSTestExtensions

    High level instructions, download the assembly and inherit from BaseTest and you can use the Assert.Throws() syntax.

    The main method for the Throws implementation looks as follows:

    public static void Throws<T>(Action task, string expectedMessage, ExceptionMessageCompareOptions options) where T : Exception
    {
        try
        {
            task();
        }
        catch (Exception ex)
        {
            AssertExceptionType<T>(ex);
            AssertExceptionMessage(ex, expectedMessage, options);
            return;
        }
    
        if (typeof(T).Equals(new Exception().GetType()))
        {
            Assert.Fail("Expected exception but no exception was thrown.");
        }
        else
        {
            Assert.Fail(string.Format("Expected exception of type {0} but no exception was thrown.", typeof(T)));
        }
    }
    

    More info here.

    0 讨论(0)
  • 2021-01-04 06:01

    Since the MSTest [ExpectedException] attribute doesn't check the text in the message, your best bet is to try...catch and set an Assert on the exception Message / ParamName property.

    0 讨论(0)
提交回复
热议问题