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?

3 Answers3

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.

pfx
  • 20,323
  • 43
  • 37
  • 57
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)

Bredjo
  • 19
  • 6
0

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
    }
}