Sharing Our Passion for Technology
& continuous learning
〈  Back to Blog

NUnit Addins That Work With Resharper

If you’ve tried to create an NUnitAddin that works with Resharper you quickly found that it simply doesn’t work.  In fact, it’s been confirmed that Resharper does not currently support NUnit EventListener addins.  While this is true, I’ve found a work around that works very nicely. Instead of adding an EventListener directly, add an ITestDecorator first.

    [NUnitAddin]
    public class CustomDecorator:IAddin, ITestDecorator
    {
        public bool Install(IExtensionHost host)
        {
            var testDecorators = host.GetExtensionPoint("TestDecorators");
            if (testDecorators == null) return false;
            testDecorators.Install(this);
            return true;
        }

        public Test Decorate(Test test, MemberInfo member)
        {
            if (test.GetType() == typeof(NUnitTestMethod) &&
                ((NUnitTestMethod)test).Method.
                    GetCustomAttributes(typeof(IgnoreAttribute), true).
                    Length == 0)
            {
                return new TestMethodWrapper((NUnitTestMethod) test);
            }
            return test;
        }

    }

In this example I only wrap tests that are of the type ‘NUnitTestMethod’. I also found that methods that were marked with Ignore were not being ignored, so I added an attribute check.

    public class TestMethodWrapper : NUnitTestMethod
    {

        private Test _test;

        public TestMethodWrapper(NUnitTestMethod testMethod) :
                     base(testMethod.Method)
        {
            _test = testMethod;
        }

        public override TestResult Run(EventListener listener,
                                                   ITestFilter filter)
        {
            return base.Run(new CustomEventListener(listener), filter);
        }

    }

The ‘TestMethodWrapper’ wraps Resharper’s EventListener with my own ‘CustomEventListener’.

    public class CustomEventListener:EventListener
    {
        private EventListener _eventListener;

        public CustomEventListener(EventListener eventListener)
        {
            _eventListener = eventListener;
        }

        ...

        public void TestFinished(TestResult result)
        {
            if (_eventListener != null)
                _eventListener.TestFinished(result);
            //do something
        }

       ...
    }

Since this ‘EventListener’ could be called outside of Resharper where there may not be an preexisting ‘EventListener’, I wrapped my delegating call with a null check.

If you’re only running your tests in the NUnit GUI console because your ‘EventListner’ is not run by Resharper, I hope this work around helps you run your tests in Visual Studio again.

〈  Back to Blog