dotnet / dotnet/docs

About arrange instances and mocks in Constructor Test classes

Open
#31,295 2 comments 0 reactions 0 assignees View on GitHub
:watch: Not Triaged dotnet-fundamentals/svc
Dominant language
No language data
Stars
4.8k
Forks
6.1k
Avg merge
15h 21m
Merged PRs (30d)
370

Description

[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):](https://xunit.net/docs/shared-context)

`public class StackTests : IDisposable
{
Stack stack;

public StackTests()
{
stack = new Stack();
}

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.*

* ID: 51947dc8-9ae8-21fa-13db-a7ffb3f9bc0e
* Version Independent ID: be661bf5-6f6e-cd18-344b-253edf5751ae
* Content: [Best practices for writing unit tests - .NET](https://learn.microsoft.com/en-us/dotnet/core/testing/unit-testing-best-practices)
* Content Source: [docs/core/testing/unit-testing-best-practices.md](https://github.com/dotnet/docs/blob/main/docs/core/testing/unit-testing-best-practices.md)
* Product: **dotnet-fundamentals**
* GitHub Login: @jpreese
* Microsoft Alias: **wiwagn**

Contributor guide

Open the contributing guide

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.