views:

36

answers:

1

How can you assert that an expected type is returned when it is wrapped up in a System.RuntimeType?

As part of a larger unit test to verify that an action has the correct parameters and action filters assigned I'm asserting against a populated instance of MethodInfo. When I assert against "action.ReturnParameter" it fails as it's saying the type is System.RunTimeType. Whilst I understand that this is a wrapper around the expected type, I just can't seem to find a way to assert that the wrapped instance is of the expected type - the best method that I've come up with so far is to assert against name or full name, but that's horrible as it's just using "magic strings".

Can anyone help? As my Google searches haven't turned up anything useful, I'm guessing it's got a really easy solution, I'm just not seeing it.

The code is as follows:

[TestMethod]
public void CheckActionFilterSet()
{
    MethodInfo action = new CustomerController((new MockHttpContext()).Object)
                                .GetType().GetMethods(BindingFlags.Public | BindingFlags.Instance)
                                .Where(mi => mi.Name.Equals("Search")).First();
    Assert.That(action.ReturnParameter.ParameterType, Is.InstanceOf(typeof(ViewResult)), "View Result should be of expected type");
}

Exception message is:

View Result should be of expected type

Expected: instance of

<System.Web.Mvc.ViewResult>

But was:

<System.RuntimeType>

+2  A: 

Just call the controller method and check the type of the object that is returned:

var result = new CustomerController((new MockHttpContext()).Object).Search(....);

Assert.That(result, Is.InstanceOf(typeof(ViewResult)), "View Result should be of expected type");

You can also check the values of ViewData / model if you want to...

Jakub Konecki
Yes, that would have been the way I used to do it. I was just hoping there was a way to do it off the populated instance of methodInfo as it would appear to sit better with that test. Then I wouldn't have to worry about checking the return type when testing the functionality of the call itself.
Paul Hadfield
But you can't check statically the type of the object that is returned at run time. You only check the return type the method is declared with. For example a method with return type of ActionResult may return a view (ViewResult) in one case or an instance of RedirectToRouteResult when user is not logged in. Your test should be testing this.
Jakub Konecki
@Jakub: Of course, that makes perfect sense. Thanks
Paul Hadfield