Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to NUnit test for a method's attribute existence

   public interface IMyServer
    {
        [OperationContract]
        [DynamicResponseType]
        [WebGet(UriTemplate = "info")]
        string ServerInfo();
    }

How do I write an NUnit test to prove that the C# interface method has the [DynamicResponseType] attribute set on it?

like image 922
John E Avatar asked Jan 05 '10 16:01

John E


People also ask

How would you determine if a class has a particular attribute?

The same you would normally check for an attribute on a class. Here's some sample code. typeof(ScheduleController) . IsDefined(typeof(SubControllerActionToViewDataAttribute), false);

Which attribute is used to mark the test methods for unit testing in NUnit?

The Test attribute is one way of marking a method inside a TestFixture class as a test. It is normally used for simple (non-parameterized) tests but may also be applied to parameterized tests without causing any extra test cases to be generated.

Which attribute is used to run the test before each test method is called in NUnit?

This attribute is used inside a TestFixture to provide a common set of functions that are performed just before each test method is called.

Which attributes point to the method to be executed after every test method?

Action Attributes allow the user to create custom attributes to encapsulate specific actions for use before or after any test is run.


1 Answers

Something like:

Assert.IsTrue(Attribute.IsDefined(
            typeof(IMyServer).GetMethod("ServerInfo"),
            typeof(DynamicResponseTypeAttribute)));

You could also do something involving generics and delegates or expressions (instead of the string "ServerInfo"), but I'm not sure it is worth it.

For [WebGet]:

WebGetAttribute attrib = (WebGetAttribute)Attribute.GetCustomAttribute(
    typeof(IMyServer).GetMethod("ServerInfo"),
    typeof(WebGetAttribute));
Assert.IsNotNull(attrib);
Assert.AreEqual("info", attrib.UriTemplate);
like image 140
Marc Gravell Avatar answered Sep 17 '22 17:09

Marc Gravell