Saving Time with the DataTestMethod Attribute

Automated testing has come a long way over the years. I remember using NUnit back in the early days of .NET when you needed a separate application to run unit tests. Since then, support for automated testing has improved to the point where we can run unit tests right from within Visual Studio. In this blog post, I will introduce you to an attribute that makes it easier to write tests that use lots of data.

Automated tests provide a lot of benefits, but one thing that can cause pain with them is that these tests require quite a bit of initial setup. Sometimes you will end up creating more code to set up the test than the actual test itself.

For example, let’s assume we have written the most amazing method ever, Adder. It adds two numbers. If we want to test this method, we will end up potentially creating a lot of methods for each scenario.

With the DataTestMethod attribute, we can just put these data parameters in an attribute on the method itself. This method is built into the MS Test framework, which means we don’t have to add anything – it just works right out of the box.

Now for a more realistic example. Here we are testing a scheduling engine. This test requires us to create a project with some activities. Doing this over and over will create a lot of methods and a lot of repetition.

We can instead use the DataTestMethod, this time paired with the Dynamic attribute, to test our schedule engine.

The ability to pass data into automated tests doesn’t enable any new abilities. We could do this without these attributes. But it does make writing and maintaining our automated tests easier.

author avatar
Chad Michel Senior Software Architect
Chad is a lifelong Nebraskan. He grew up in rural Nebraska and now lives in Lincoln. Chad and his wife have a son and daughter.

Related posts