Reuse Your Parametrised Test Inputs With TestCaseSource in NUnit

As we saw last week, parametrised tests help us to reduce the number of test methods we have to write and still keep the coverage high. However, writing the test parameters multiple times is error prone, especially when it is important that we test all values. Let us look on how NUnit can help us with this problem.

 

The [TestCaseSource] attribute

With the [TestCaseSource] attribute we can tell NUnit that our data for the parametrised test comes from a property or a method. Instead of a [TestCase] for every test, we write one singe [TestCaseSource]:

There are 3 important points you must follow when you create a test case source:

  1. It must be static.
  2. It must return an IEnumerable or a type that implements IEnumerable
  3. The returned items must be compatible with the method signature

NUnit does a lot of work in the background. If something goes wrong, read the documentation to see if you missed something.

 

Use test data from another class

You can reuse your test data outside of the class you wrote it. In my class ExternalTestData I have a property and a method that provides the test cases:

In our test class we can reference the test data by putting the name of the class in front of the property / method:

 

Conclusion

Parametrised tests, especially in combination with TestCaseSource, are a great tool to keep the overhead of writing test methods down. They may not look like much work, but as soon as you need to change them, you hope that you used parametrised tests and only need to change a few lines of code. Now would be a good time to start using parametrised tests if you not already do.

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.