xUnit shared context by private static fields

Viewed 105

What disadvantages have an approach of sharing context by creating private static fields?

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?

1 Answers

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.

Related