xUnit - Strongly Typed Test Data

30 Jun 2019 By Christian Findlay

Hire me to elevate your .NET codebase

Build Microservices • Unit Testing

Upgrade to .NET 8 • CI / CD

Contact me today

xUnit has a quirky system for consuming test data. Strongly typed test data can be specified with the MemberData attribute and the Theory attribute but it’s not intuitive.

The MemberData attribute allows you to specify a getter that returns an enumeration of object arrays. It expects the type to be IEnumerable<object[]>. The trick is to return a List with multiple object arrays in it. Here is some example code for the getting the strongly typed test data. This makes for much cleaner unit testing.

This repo can be cloned here. This is the source code for the unit test.

The getter for the test data:

Test Data Method

This is the SampleData class:

Sample Data Class

This is how your unit test can consume the strongly typed data: