Decorate Your Tests


In my last post I showed you how to write a minimal NUnit addin. It didn’t do anything useful, so let’s see what we can do with test decorators.

What Is a Test Decorator?

The Decorator Pattern describes a design for attaching additional responsibilities to an object dynamically. It is also known as Wrapper. Test Decorators wrap a single test case or a test fixture and therefore allow you to run some code before and after it.

Typical uses for test decorators are measuring performance or setting up and cleaning up a database.

Copy a File Before Running a Test

Assume that a test needs a certain file each time you run a test. If those tests are in the same test fixture and there are no other tests in this fixture, you will use a setup method. Otherwise test decorators may help you. Furthermore test decorators provide a way to share test extensions.

So, let’s start by writing an NUnit addin:

    [NUnitAddin(Name="Copy File Decorator Addin",
                Description="Copies a file before running the test.")]
    public class CopyFileAddin : IAddin, ITestDecorator
      public bool Install(IExtensionHost host)
        IExtensionPoint decorators = host.GetExtensionPoint("TestDecorators");
        if (decorators == null)
          return false;
        return true;

As CopyFileAddin implements both the IAddin and the ITestDecorator interfaces, it installs itself at the extension point “TestDecorators”. I described the IAddin interface in my last post and ITestDecorator declares the method Decorate and CopyFileAddin implements it as follows:

    public Test Decorate(Test test, MemberInfo member)
      // Decorate only single test cases
      if (test is TestCase)
        Attribute attribute = Reflect.GetAttribute(
            member, "CopyFileTest.Framework.CopyFileAttribute", false);
        if (attribute != null)
          string sourcePath = (string)Reflect.GetPropertyValue(attribute, 
              "SourcePath", BindingFlags.Public | BindingFlags.Instance);
          string destinationPath = (string)Reflect.GetPropertyValue(attribute, 
              "DestinationPath", BindingFlags.Public | BindingFlags.Instance);
          test = new CopyFileTestCase((TestCase) test,
              sourcePath, destinationPath);
      return test;

In NUnit 2.4 you mark tests to be wrapped by using specific .NET attributes. The test decorator extension identifies those tests and wrap them with a special decorator test case class, e.g. the following test case will be wrapped with a CopyFileTestCase if the CopyFileAddin is properly installed in your NUnit – in my last post I described how to do this.

The attribute CopyFile marks the test case to be wrapped and stores the source and destination path of the file to be copied. The test may be run in another thread, so the paths must be absolute.

The decorator class looks like this:

    public class CopyFileTestCase : TestCase
      private TestCase _testCase;
      private string _sourceFilePath;
      private string _destinationPath;
      public CopyFileTestCase(
          TestCase testCase,
          string sourceFilePath,
          string destinationPath)
          : base((TestName)testCase.TestName.Clone())
        _testCase = testCase;
        _sourceFilePath = sourceFilePath;
        _destinationPath = destinationPath;
      public override void Run(TestCaseResult result)
        if (File.Exists(_sourceFilePath))
          File.Copy (_sourceFilePath, _destinationPath);
        if (File.Exists(_destinationPath))

Test Cases And Test Suites

Maybe you are wondering, what the classes Test and TestCase are about. NUnit organizes tests in test cases and test suites and both are tests. They form another design pattern known as Composite.

Test, TestCase and TestSuite

If your decorator supports single test cases only it will wrap a TestCase, like CopyFileTestCase. You may decorate test suites or both test cases and test suites by wrapping a TestSuite or Test object respectively.

RepeatedTestDecorator and MaxTimeDecorator

NUnit 2.4 already provides a test decorator: the RepeatedTestDecorator. You can find it in the assembly “nunit.framework.extensions.dll”.

    using System;
    using NUnit.Framework;
    using NUnit.Framework.Extensions;
    namespace RepeatedTest
      public class RepeatedTestFixture
        private int _count;
        public void TestFixtureSetUp()
          _count = 0;
        public void RepeatedTestCase()
          if (_count == 5)
            Assert.Fail("The test has been repeated 5 times.");

You will have to reference the assembly “nunit.framework.extensions.dll”. The test will fail with the
provided message. The NUnit package installs some sample projects and amongst them a solution with examples for the new Core Extensibility features. There you can find the sample decorator MaxTimeDecorator, which fails a test when its duration exceeds a provided limit.


Currently there is no way to specify an Addin as requirement. Imagine, you’ve written a unit test using the MaxTimeDecorator. Your test will fail if it runs longer than the provided limit. You
commit your changes to your source repository. Your colleague gets the new unit test from the repository and works on the program. Her changes affect the performance of the code and the test lasts longer than required. If she didn’t install the MaxTimeDecorator Addin, she would not notice the defect.

There is currently no mechanism to control the order in which the decorators are applied. NUnit applies decorators in the order in which they are returned through reflection. Therefore pay attention to this issue if you use more than one decorator.

    public void RepeatedTestCase()
      if (_count == 5)
        Assert.Fail("The test has been repeated 5 times.");

In this example it is not predictable if the test will fail because of the counter or the exceeded time limit. If the RepeatDecorator wraps the MaxTimeDecorator, it will fail because of the counter, otherwise because of the time limit.

More Information

If you need more information about NUnit addins, have a look at the NUnit documentation.

234 thoughts on “Decorate Your Tests

  1. wh0cd12608 [url=]avalide[/url] [url=]propranolol[/url] [url=]tadalafil[/url] [url=]tadalafil 5mg[/url] [url=]prednisolone[/url] [url=]diclofenac sodium 75 mg[/url] [url=]generic antabuse online[/url] [url=]buy mobic[/url] [url=]betnovate cream[/url] [url=]order sildenafil online[/url]

  2. wh0cd12608 [url=]colchicine brand name[/url] [url=]antabuse tablets[/url] [url=]prednisolone[/url] [url=]generic doxycycline[/url] [url=]resources[/url] [url=]elavil medicine[/url]

  3. wh0cd12608 [url=]propecia[/url] [url=]order hydrochlorothiazide[/url] [url=]order cialis[/url] [url=]buy tadalis sx[/url]

  4. DarrellGok

    Get uр tо $ 20,000 реr daу with our рrоgrаm.
    Wе аrе a tеam оf еxperienсed prоgrаmmеrs, wоrked mоre than 14 mоnths оn this program and nоw evеrуthing is rеаdy and еverуthing wоrks реrfectlу. The PaуРаl sуstеm is vеrу vulnеrable, instеаd of notifying thе dеvеlopers of РaуРal аbout this vulnеrаbility, we took advantаge of it. We activеlу usе our рrоgram fоr pеrsоnal еnriсhmеnt, to shоw huge amounts оf mоnеу on our aсcounts, wе will not. you will nоt beliеve until уou try and аs it is not in оur intеrest tо provе tо уоu thаt something is in уours. Whеn wе reаlized that this vulnerаbilitу cаn bе usеd massively withоut соnsеquenсes, wе decided tо helр the rеst of the pеорle. Wе dеcided nоt to inflаtе thе рrice оf this gоld prоgram аnd put а verу lоw pricе tаg, оnly $ 550. In оrder fоr this рrоgram to be аvаilablе to а lаrge numbеr оf peорlе.
    All thе dеtаils on our blоg:

  5. ScottSed

    Hеllо! I’ll tell уou my method with аll the dеtails, as I stаrtеd еarning in the Intеrnet from $ 3,500 per day with the hеlp of sоcial nеtworks reddit and twittеr. In this vidео you will find morе dеtаilеd infоrmаtion and аlsо seе how mаny milliоns have earned thоsе who have bееn wоrking fоr а yеar using mу method. I sрeсificallу mаdе a videо in this сaраcitу. Аftеr buуing my mеthоd, yоu will undеrstаnd why:

  6. Thanks on your marvelous posting! I actually enjoyed reading
    it, you happen to be a great author.I will ensure that I
    bookmark your blog and definitely will come back in the foreseeable future.
    I want to encourage continue your great posts, have a nice holiday weekend!

  7. JAXAで働きたいというかたは、意外と多いです。

  8. After exploring a few of the articles on your website, I truly appreciate your technique of blogging.
    I saved as a favorite it to my bookmark webpage list and will be checking back in the
    near future. Take a look at my website as well and tell me your

  9. wonderful submit, very informative Decorate Your Tests – Andreas Schlapsi .

    I ponder why the opposite experts of this sector don’t realize this Decorate Your Tests – Andreas Schlapsi .
    You must continue your writing Decorate Your Tests
    – Andreas Schlapsi . I’m sure, you have a huge
    readers’ base already!

  10. I’m really enjoying the design and layout of your site. It’s a very easy on the eyes which makes it much more pleasant for me to come here and visit more often. Did you hire out a designer to create your theme? Great work!

  11. Most of what you assert is astonishingly precise and it makes me ponder the reason why I had not looked at this in this light before. This piece truly did turn the light on for me as far as this issue goes. Nonetheless at this time there is just one position I am not too cozy with so whilst I try to reconcile that with the core theme of the position, allow me observe what the rest of your subscribers have to say.Nicely done.

  12. Thanks for the sensible critique. Me & my neighbor were just preparing to do some research about this. We got a grab a book from our area library but I think I learned more clear from this post. I am very glad to see such wonderful information being shared freely out there.

  13. Thank you for another informative blog. Where else may I am getting that type of info written in such a perfect approach? I’ve a project that I’m just now operating on, and I have been on the glance out for such information.

  14. hello there and thank you for your information ? I have definitely picked up anything new from right here. I did however expertise a few technical issues using this website, as I experienced to reload the web site many times previous to I could get it to load properly. I had been wondering if your web hosting is OK? Not that I’m complaining, but sluggish loading instances times will often affect your placement in google and could damage your quality score if ads and marketing with Adwords. Anyway I?m adding this RSS to my email and can look out for much more of your respective fascinating content. Make sure you update this again soon..

  15. You can definitely see your skills in the work you write. The world hopes for even more passionate writers such as you who are not afraid to say how they believe. All the time go after your heart.

  16. Howdy just wanted to give you a quick heads up. The words in your article seem to be running off the screen in Chrome. I’m not sure if this is a formatting issue or something to do with browser compatibility but I thought I’d post to let you know. The design and style look great though! Hope you get the problem solved soon. Cheers

  17. Can I simply say what a aid to seek out somebody who actually is aware of what theyre speaking about on the internet. You definitely know how to deliver an issue to gentle and make it important. Extra individuals have to read this and perceive this facet of the story. I cant believe youre no more common since you definitely have the gift.

  18. I’m not sure where you’re getting your info, but good topic.
    I needs to spend some time learning much more or understanding more.
    Thanks for excellent information I was looking for this information for my mission.

  19. After going over a number of the blog posts on your blog,
    I seriously like your technique of writing a blog. I saved as a
    favorite it to my bookmark website list and will be checking back in the near
    future. Please check out my website as well and
    let me know your opinion.

  20. Hiya, I’m really glad I’ve found this info. Today bloggers publish only about gossips and net and this is actually irritating. A good blog with interesting content, this is what I need. Thank you for keeping this web site, I’ll be visiting it. Do you do newsletters? Can not find it.

  21. Nice post. I discover something very complicated on distinct blogs everyday. Most commonly it is stimulating to read content off their writers and use a specific thing from their store. I’d would rather apply certain with all the content on my own blog no matter whether you do not mind. Natually I’ll supply you with a link for your internet weblog. Many thanks sharing.

  22. I spent four years trying EVERYTHING in Online Dating, and through a huge amount of trial and error, I produced a system that I will share for you. This book will take you, step by step, through everything you need to know to double, triple or even quadruple the number of women you meet online.

  23. I just want to tell you that I am all new to blogs and definitely savored your web site. Very likely I’m likely to bookmark your website . You actually have superb stories. Thanks for revealing your web page.

  24. I spent four years trying EVERYTHING in Online Dating, and through a huge amount of trial and error, I produced a system that I will share for you. This book will take you, step by step, through everything you need to know to double, triple or even quadruple the number of women you meet online.

  25. The internet insurance estimates allow individuals to take over questionnaires anytime. The principal thing they’ve to become is which you can follow the approach to obtain a particular estimate the auto insurance cover.

  26. I was more than happy to find this net-site.I wished to thanks to your time for this excellent learn!! I positively having fun with each little bit of it and I’ve you bookmarked to take a look at new stuff you blog post.

Leave a Reply

Your email address will not be published.