Skip to content

Assert.Throws should print the actual exception. #6906

Description

@nohwnd

Summary

 Assert.Throws failed. Expected exception type:<System.ArgumentException>. Actual exception type:<System.InvalidOperationException>. 'action' expression: '() => new MyClass().MyMethod()'.
    at Microsoft.VisualStudio.TestTools.UnitTesting.Assert.<>c__DisplayClass226_1`1.<IsThrowsFailing>b__1(String userMessage) in /_/src/TestFramework/TestFramework/Assertions/Assert.ThrowsException.cs:581
    at Microsoft.VisualStudio.TestTools.UnitTesting.Assert.ThrowsException[TException](Action action, Boolean isStrictType, String message, String actionExpression, String assertMethodName) in /_/src/TestFramework/TestFramework/Assertions/Assert.ThrowsException.cs:330
    at Microsoft.VisualStudio.TestTools.UnitTesting.Assert.Throws[TException](Action action, String message, String actionExpression) in /_/src/TestFramework/TestFramework/Assertions/Assert.ThrowsException.cs:187
    at mstest306.Test1.TestMethod1() in Test1.cs:9
    at System.Reflection.MethodBaseInvoker.InterpretedInvoke_Method(Object obj, IntPtr* args)
    at System.Reflection.MethodBaseInvoker.InvokeWithNoArgs(Object obj, BindingFlags invokeAttr)
bin\Debug\net10.0\mstest306.dll (net10.0|x64) failed with 1 error(s) (566ms)

is what I see currently when Assert.Throws fails. This is not giving it all the information I need to find the failure, and forces me to guess where the error happened. Am I seeing the friday error, or other error? what if the problem is not easily replicable?

Instead it would be nice if we reported the whole exception, so I can see the message and stack trace of the unexpected exception, and maybe solve this problem without debugging .

// file Test1.cs
namespace mstest306;

[TestClass]
public sealed class Test1
{
    [TestMethod]
    public void TestMethod1()
    {
        Assert.Throws<ArgumentException>(() => new MyClass().MyMethod());
    }
}

public sealed class MyClass
{
    public void MyMethod ()
    {
        Helper.HelperMethod();
    }
}

public static class Helper
{
    public static void HelperMethod()
    {

        if (DateTime.Now.DayOfWeek.ToString() == "Friday")
        {
            throw new InvalidOperationException("the error");
        }   
        else
        {
            throw new InvalidOperationException("the other error");
        } 
    }
}

Metadata

Metadata

Assignees

No one assigned

    Labels

    area/assertionAssert / StringAssert / CollectionAssert APIs.area/mstestMSTest framework (not analyzers or assertions).

    Fields

    No fields configured for Feature.

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions