1

Is there any way to create method that will be automatically called before any test?

[Fact] public void Test1() { } [Fact] public void Test2() { } private void Prepare() { // Prepare test environment } 

I need Prepare to be called before Test1 and Test2. It should be like this:

  1. Call Prepare()
  2. Call Test1
  3. Call Prepare()
  4. Call Test2

I know that i can call it by my own like

[Fact] public void Test1() { Prepare(); } 

but is there any way to do it automatically?

1

3 Answers 3

2

Include that call to the Prepare method in the constructor of your test class.

The documentation comparing other testing frameworks that have e.g. a [SetUp] attribute or alike mentions below.

We believe that use of [SetUp] is generally bad. However, you can implement a parameterless constructor as a direct replacement.

Sign up to request clarification or add additional context in comments.

2 Comments

That does not work if the setup has async code
@DavidThielen That's true. In case you would need an async setup, than have a look at xUnit's IAsyncLifetime interface having an Task InitializeAsync method. That's rather out of scope for this question.
1

You could call Prepare method in the construtor of the class. So it will be called automatically before tests methods.

public class ClassTest { public ClassTest() { Prepare(); } public void Prepare() { // your logic } [Fact] public void Test1() { //Arrange //Act //Assert } } 

Comments

0

In NUnit there is an SetUp attribute that you can use for a method, that should be run before any test.

In xUnit it seems like, that you need to create this by yourself (see here)

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.