xUnit.net shared test context

The test context setup is done in the test class constructor, since the test setup is not applicable in xUnit. For every test, xUnit creates a new instance of the test class, which implies that the codes in the class constructor are run for each test.

Oftentimes, it is desirable for unit test classes to share a test context because it can be expensive to create and clean up test contexts. xUnit offers three approaches to achieve this:

  • Constructor and dispose: Sharing setup or cleanup code without having to share the object instances
  • Class fixtures: Sharing object instances across tests in a single class
  • Collection fixtures: Sharing object instances across multiple test classes

You should use constructor and ...

Get C# and .NET Core Test Driven Development now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.