Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

RuntimeType instead of Type in C# Unit Test

In one of my unit tests I want to check if all public methods are returning type of ActionResult. Here's my test method:

    [TestMethod]
    public void Public_Methods_Should_Only_Return_ActionResults()
    {

        MethodInfo[] methodInfos = typeof(MyController).GetMethods(BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly);

        foreach (MethodInfo methodInfo in methodInfos)
        {
            Assert.IsInstanceOfType(methodInfo.ReturnType, typeof(System.Web.Mvc.ActionResult));

        }

    }

This test blows up on the first method from MyController:

[Authorize]
public ActionResult MyList()
{
    return View();
}

With the following error:

Assert.IsInstanceOfType failed. Expected type:<System.Web.Mvc.ActionResult>. Actual type:<System.RuntimeType>.  

When I set a breakpoint on that Assert and check the methodInfo.ReturnType it is of type Type and it is ActionResult.

Can anyone explain me why the test is blowing up and what to do to make it work?

Thanks in advance, MR

like image 574
Michal Rogozinski Avatar asked Jul 30 '09 20:07

Michal Rogozinski


1 Answers

Use Assert.AreEqual instead of Assert.IsInstanceOfType. You want to check the type of the result, not the type of the reflected type info.

like image 107
Craig Stuntz Avatar answered Sep 22 '22 07:09

Craig Stuntz