dotnet / docs

This repository contains .NET Documentation.
https://learn.microsoft.com/dotnet
Creative Commons Attribution 4.0 International
4.27k stars 5.9k forks source link

About arrange instances and mocks in Constructor Test classes #31295

Open ronaldoperes opened 2 years ago

ronaldoperes commented 2 years ago

[Enter feedback here] I found this site through a colleague,

Usually I follow almost all those practices, but what can you tell me about setting up the "Arrange" part in the constructor of the test class? Is this a bad practice?

I found how to use it on Xunit documentation, but I didn't find about it telling that is a bad practice.

Example from Xunit docs (Xunit shared-context):

`public class StackTests : IDisposable { Stack stack;

public StackTests()
{
    stack = new Stack<int>();
}

public void Dispose()
{
    stack.Dispose();
}

[Fact]
public void WithNoItems_CountShouldReturnZero()
{
    var count = stack.Count;

    Assert.Equal(0, count);
}

[Fact]
public void AfterPushingItem_CountShouldReturnOne()
{
    stack.Push(42);

    var count = stack.Count;

    Assert.Equal(1, count);
}

}`


Document Details

Do not edit this section. It is required for docs.microsoft.com ➟ GitHub issue linking.

jpreese commented 2 years ago

I prefer to avoid using the constructor to setup and teardown tests, and tend to keep everything required by the test defined in the test itself. Otherwise it can be hard to see how the test is being setup, how variables are defined, etc without having to go find the constructor.

If I need this sort of behavior, I instead use some test helper method that sets everything up for me, but still keeps the entire Arrange step within the test.

ronaldoperes commented 2 years ago

I prefer to avoid using the constructor to setup and teardown tests, and tend to keep everything required by the test defined in the test itself. Otherwise it can be hard to see how the test is being setup, how variables are defined, etc without having to go find the constructor.

If I need this sort of behavior, I instead use some test helper method that sets everything up for me, but still keeps the entire Arrange step within the test.

Ok, but and if I have same parameters for a class constructor between different classes?

Should I use helper methods or the Fixture Feature from XUnit?