Assert exception from NUnit to MS TEST

后端 未结 3 1161
终归单人心
终归单人心 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: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(Action task, string expectedMessage, ExceptionMessageCompareOptions options) where T : Exception
    {
        try
        {
            task();
        }
        catch (Exception ex)
        {
            AssertExceptionType(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.

提交回复
热议问题