[EN] TestDataSource annotation included in nUnit is useful sometime

Sometimes when you write tests you want to check how the code behaves in different cases. I had already experienced that a couple of times before and I always used TestCase annotation available in nUnit library.

It’s nice to know that nUnit offers an alternative approach as well. You can use TestCaseSource annotation instead of TestCase to prepare test cases. There is a slight difference between those two approaches and official documentation of nUnit delivers clear explanation:

TestCaseAttribute serves the dual purpose of marking a method with parameters as a test method and providing inline data to be used when invoking that method.


 TestCaseSourceAttribute is used on a parameterized test method to identify the property, method or field that will provide the required arguments.


Though it looks similar I’ve found an additional benefit offered by TestCaseSource annotation. It allows you to pass more complex objects (or collection of objects) to your test method. In some cases it is extremely helpful and it increases readability of your tests. I will show you a real-life example from my experience. Once I wanted to pass a quite complex POCO object as an argument to the test method. It looked as follows:

In this case usage of TestCase annotation was unhandy and it looked like this:

The sample above looks bad, moreover if I would prepare another test with similar cases I brake DRY rule because I have to copy and paste a lot of code.

TestCaseSource simplified the code of the test and increased readability (because I was able to move test case data into separate place). The same example with TestCaseSource instead of TestCase annotation:

Here you can see how I used it in my project. I would recommend using TestCaseSource annotation in case when you have to pass many parameters (for example more than 4) or a complex object (like the above example).

Say something

Your email address will not be published. Required fields are marked with a grey bar.

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code class="" title="" data-url=""> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong> <pre class="" title="" data-url=""> <span class="" title="" data-url="">