'xUnit shared context by private static fields
What disadvantages have an approach of sharing context by creating private static
fields? If I don't need to call Dispose
?
public class MyTests3 : IDisposable
{
private static Mock<ILogger> _loggerMock = new Mock<ILogger>();
public void Dispose()
{
_loggerMock.Invocations.Clear();
}
[Fact]
public void Debug_OnInit_CalledOnce()
{
// arrange & act
_loggerMock.Object.Debug("first");
// assert
_loggerMock.Verify(l => l.Debug(It.IsAny<string>()), Times.Once);
}
[Fact]
public void Debug_OnExecute_CalledOnce()
{
// arrange & act
_loggerMock.Object.Debug("second");
// assert
_loggerMock.Verify(l => l.Debug(It.IsAny<string>()), Times.Once);
}
}
The other question - should I call Reset
for mock objects after the test is done?
Solution 1:[1]
You should avoid sharing state between tests. It can create unwanted and unpredictable behavior, especially when your tests run in parallel.
It's one of the reason for the prefer-helper-methods-to-setup-and-teardown best practice.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Batesias |