© 2026 Hedgehog Software, LLC

TwitterGitHubDiscord
More
CommunitiesDocsAboutTermsPrivacy
Search
Star
Setup for Free
C#C
C#•12mo ago•
3 replies
Faker

Unit Test, TestInitialize alternative in xUnit

Hello guys, I read that [TestInitialize] is used in MSTest to initialize an object. My first question is why should we initialize it? I mean, it seems that we build an entire method to initialize it, why not initializing it in the test cases?

Second thing, when each test cases is executed, the TestInitialize attribute creates a new instance for each case? The idea is we don't want shared data to affect our result?

I read a bit and came across how we can mimic TestInitialize in xUnit:

namespace Week7Lab.UnitTest;


using Week7Labs;
public class OrderProcessorTest : IDisposable
{
    private OrderProcessor _processor;

    public OrderProcessorTest()
    {
        _processor = new OrderProcessor();
    }
    [Fact]
    public void CalculateTotal_WithValidOrder_ReturnsCorrectTotal()
    {
        // Arrange
        var listOfItems = new Items[1];
        var it = new Items();
        var order = new Order();
        it.Quantity = 10;
        it.Price = 100;
        listOfItems[0] = it;
        order.Items = listOfItems;
        // Act
        var result = _processor.CalculateTotal(order);
        // Assert
        Assert.Equal(1000, result);
    }

    public void Dispose()
    {
        //
    }
}
namespace Week7Lab.UnitTest;


using Week7Labs;
public class OrderProcessorTest : IDisposable
{
    private OrderProcessor _processor;

    public OrderProcessorTest()
    {
        _processor = new OrderProcessor();
    }
    [Fact]
    public void CalculateTotal_WithValidOrder_ReturnsCorrectTotal()
    {
        // Arrange
        var listOfItems = new Items[1];
        var it = new Items();
        var order = new Order();
        it.Quantity = 10;
        it.Price = 100;
        listOfItems[0] = it;
        order.Items = listOfItems;
        // Act
        var result = _processor.CalculateTotal(order);
        // Assert
        Assert.Equal(1000, result);
    }

    public void Dispose()
    {
        //
    }
}

I write something like this. Can anyone confirm whether the idea is correct please.

Also, notice that we implement the IDisposable, why is it necessary here?
C# banner
C#Join
We are a programming server aimed at coders discussing everything related to C# (CSharp) and .NET.
61,871Members
Resources

Similar Threads

Was this page helpful?
Recent Announcements

Similar Threads

✅ Weird unit testing issue in xUnit
C#CC# / help
6mo ago
❔ Unit testing xUnit, NSubstitute and FluentAssertion.
C#CC# / help
3y ago
[XUnit, Moq, EFCore] Unit Testing Question
C#CC# / help
4y ago
Unit test help
C#CC# / help
17mo ago