C
C#6d ago
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:
C#
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()
{
//
}
}
C#
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?
2 Replies
Sehra
Sehra6d ago
https://thomhurst.github.io/TUnit/docs/comparison/attributes has a comparison table, lifecycle hook attributes if you have lots of common things to initialize, you can mark a method and you don't have to call it yourself in each test
Faker
FakerOP6d ago
yep I see

Did you find this page helpful?