C
C#17mo ago
Sossenbinder

❔ xUnit single setup and teardown

Hello, So, I'm currently in the progress of switching from NUnit to XUnit and I was wondering how I could achieve this behaviour: I have a test class containing around 10 integration tests. This class inherits from a base class which prepares test containers for this context. The goal would be: - Call the base classes constructor once, which prepares the testcontainer - For every test, call an initialize to start the container before the test, and a teardown to stop the container after the test - After all 10 tests ran, call a single teardown which makes sure the container is gone. With NUnit this was fairly easy, but I'm not entirely sure how to recreate this behaviour with xUnit, since it would create a new instance of the test class for every test, it also passes the testcontainer preparation logic for every invocation. There are ways around this with static fields / properties, but I don't feel like this is the clean approach here. Any advice?
7 Replies
Sossenbinder
SossenbinderOP17mo ago
I've seen that there is ICollectionFixture<T> which I can apparently put on my class, but I'm not sure if that's the right approach Maybe this is a XY problem as well in case a base class is not the xUnit way Is this where I'd use IClassFixture<T> with T managing my dependencies?
pox
pox17mo ago
Yes you want to use a fixture. You can also add IAsyncLifetime to T if you need async setup / cleanup
Sossenbinder
SossenbinderOP17mo ago
I see! Is there any way to pass parameters to T to customize the behaviour of T, or do I have to do this through some kind of static environmental configuration or inheritance?
pox
pox17mo ago
So what we do is we create a couple of "base" fixtures. Then per tests collection or what we need we inherit that base and edit the stuff we need. I can show an basic example
pox
pox17mo ago
https://gist.github.com/JockeM/ed9bf59077d16a57b59f2a9b2ffc358c not sure if the syntax is 100% correct but something like this is what we do
Gist
gist:ed9bf59077d16a57b59f2a9b2ffc358c
GitHub Gist: instantly share code, notes, and snippets.
Sossenbinder
SossenbinderOP17mo ago
I see, that's what I thought Thanks
Accord
Accord17mo ago
Was this issue resolved? If so, run /close - otherwise I will mark this as stale and this post will be archived until there is new activity.

Did you find this page helpful?