Michal Rogozinski
Michal Rogozinski

Reputation: 1759

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

Upvotes: 9

Views: 3461

Answers (1)

Craig Stuntz
Craig Stuntz

Reputation: 126587

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

Upvotes: 16

Related Questions