Unit tests and DRY

One of common things that I unit test with NUnit is testing throwing or not throwing a specific exception. This is done using Assert.Throws and Assert.DoesNotThrow. I used to write 2 method for a exception assert unit test. One that do the actual work and one for unit test previous method. Consider following:

pubic void method1()
{
int a =1;
int b=2;
//plenty setup needed here

MyClass.DoSomething(a, b);
}

[Test]
public void DoSomethingTest()
{
Assert.DoesNotThrow(method1);
}

Now suppose that you have to unit test MyClass.DoSomething against many similar inputs. One way to do is repeat method1 and DoSomethingTest as needed. A disadvantage is that it’s against DRY principle. As Assert.DoesNotThrow ony accepts methods that has not parameter, I couldn’t stop to repeat initialization/setup codes in every method.

Fortunately today I found that I can use Anonymous Methods with Assert.Throws and Assert.DoesNotThrow without need to create several methods. Using this way DRY is leveraged in unit tests. See following example:

[Test]
public void DoSomethingTest()
{
int a1 = 1;
int b1 =2;

int b2 =4;

int b3 = -1;

Assert.DoesNotThrows(delegate()
{
MyClass.DoSomething(a1, b1);
});

Assert.DoesNotThrows(delegate()
{
MyClass.DoSomething(a1, b2);
});

Assert.DoesNotThrows(delegate()
{
MyClass.DoSomething(a1, b3);
});

Note: Many others have problems with applying DRY or KISS with unit tests including this one.

دیدگاهتان را بنویسید

نشانی ایمیل شما منتشر نخواهد شد. بخش‌های موردنیاز علامت‌گذاری شده‌اند *