1

I'm using C# XUnit in Visual Studio 2019 and I have a test class with various tests, working with databases and a web app. I'd like to run some code that sets up specific DB tables prior running the tests and also cleans afterwards. The catch is that I need this code to run only before and after some specific tests.

  • Using InLine params is not possible as these tests don't work with the same content.
  • Fixtures are unusable as they work for all the tests.
  • EDIT: The tests cannot have a separate class

The ideal case is to have something like:

[For tests with trait XZ]
TestInit(){RUN CODE}

[For tests with trait XZ]
TestCleanup(){RUN CODE]

Is this possible in XUnit or is using a class with extension methods the best possibility?

RegCent
  • 98
  • 11
  • 3
    Move those specific tests into a separate test class with its own setup and teardown. – Nkosi Aug 29 '19 at 11:19
  • Thought of that, but not the solution I want, all of these tests belong together as they all test controls in the web app – RegCent Aug 29 '19 at 11:26
  • That fact that those tests require such distinctly separate setup indicates that they have separate concerns than the other tests. – Nkosi Aug 29 '19 at 11:28
  • It's changing the default account language which then changes the hours format to 12Hr+AM/PM. Other tests dont need that setup and should work with default lang setup – RegCent Aug 29 '19 at 11:31

1 Answers1

2

Check out Test Fixtures in the xUnit documentation, specifically the "test class as context" paradigm. Basically you can nest classes inside your test class that includes a constructor for pre-test setup and a Dispose method for post-test tear down.

Wesley Rolnick
  • 871
  • 4
  • 11
  • I might not understand it correctly, but does it differ from creating a separate test class in a different file? It sort of sounds the same to me – RegCent Aug 29 '19 at 11:34
  • 2
    @RegCent technically it is a separate class but that class is embedded in the main test class. Basically taking the target test methods and wrapping them in a class. – Nkosi Aug 29 '19 at 11:36
  • So far, this is the closest to the thing I had in mind :) I'm guessing there is no way to have what I described in the question and if someone definitely confirms this, I'll mark this as an answer – RegCent Aug 29 '19 at 11:42