3

I have created a custom Attribute debugging it realised that it get called so many times even I run just ONE test. Seems like it get called for attributes for all tests:

        [AttributeUsage(AttributeTargets.Method | AttributeTargets.Class |
                AttributeTargets.Interface | AttributeTargets.Assembly,
                AllowMultiple = true)]
    public class DisplayModeAttribute : Attribute, ITestAction
    {
        private readonly string screenSize;

        public DisplayModeAttribute(string screenSize)
        {
            this.screenSize = screenSize;
        }

        public void BeforeTest(TestDetails details)
        {
            PageFactory.SetWindowSize(screenSize);
        }

        public void AfterTest(TestDetails details)
        {

        }

        public ActionTargets Targets
        {
            get { return ActionTargets.Test | ActionTargets.Suite; }
        }
    }

I have Three tests that are using this attribute with small, large xsmall values as

  [DisplayMode("small")]

When I debug a test I notice that attribute constructor get called with all the values (small, large, xsmall) each for many times (around 40!). And for the final call it sets the value with the correct value e.g "small"

Checking the call stack I can't see it get called by whom.

Cœur
  • 37,241
  • 25
  • 195
  • 267
shiva
  • 714
  • 10
  • 25
  • There is post explaining when custom attribute constructor runs, based on this my constructor should get called 3 times (although they are same types of attributes with different arg). But in my case consructor get called 40 times (approx) http://stackoverflow.com/questions/1168535/when-is-a-custom-attributes-constructor-run – shiva Mar 24 '15 at 10:02
  • Where are you putting the attribute? – Ben Aston Mar 24 '15 at 23:41

1 Answers1

1

I do not know the details of this attribute, but it looks like the intention is for the attribute to be run once per test invocation. If this is the case, then an instantiation count of 40 does not sound too unreasonable.

Attributes in C# are an implementation of aspect-oriented programming which sounds like a good idea, but can quickly become difficult to understand and tough to test.

Instead of using an attribute, I would recommend using a straightforward method invocation in the test set-up, which although not as "cool" will be simpler to understand for other developers when they come to read the test suite.

If you really insist on using attributes, then try changing

get { return ActionTargets.Test | ActionTargets.Suite; }

to be

get { return ActionTargets.Suite; }
Ben Aston
  • 53,718
  • 65
  • 205
  • 331