Question

I have an MVC3 application with the below action.

public class FooController : ApplicationController
{
  [My(baz: true)]
  public void Index()
  {
    return view("blah");
  }
}

I can write a test to verify that Index is decorated with MyAttribute using MVCContrib's TestHelper in this fashion.

[TestFixture]
public class FooControllerTest
{
  [Test]
  public void ShouldHaveMyAttribute()
  {
    var fooController = new FooController();
    fooController.Allows(x => x.Index(), new List<Type>{typeof(MyAttribute)});
  }
}

Question - How can this test be changed to test that the MyAttribute decoration includes the property 'baz' to be true?

Was it helpful?

Solution

If you want to verify the attribute in your unit tests, you'll need to use reflection to inspect your controller methods as follows.

[TestFixture]
public class FooController Tests 
{
    [Test]
    public void Verify_Index_Is_Decorated_With_My_Attribute() {
        var controller = new FooController ();
        var type = controller.GetType();
        var methodInfo = type.GetMethod("Index");
        var attributes = methodInfo.GetCustomAttributes(typeof(MyAttribute), true);
        Assert.IsTrue(attributes.Any(), "MyAttribute found on Index");
        Assert.IsTrue(((MyAttribute)attr[0]).baz);
    }
}

this may help you

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top