This question regards unit testing in Visual Studio using MSTest (this is important, because of MSTest\'s execution order). Both the method marked [TestInitialize] and the t
Here are some advantages I've found with TestInitialize.
The main advantage of using either TestInitialize() or ClassInitialize() rather than the test class instance or static constructors is its explicit nature. It clearly communicates that you are doing some setup prior to your tests. Doing this consistently should improve maintainability in the long run.
I say use the constructor unless you need TestContext
.
readonly
which is a big thing in test initialization where you want to prepare stuff for the tests that they're not supposed to change (ideally the stuff you prepare would be immutable too).I hope somebody still needs that. This is my solution, how to unit test class constructor. I am unit testing class service and throwing an exception if debuggingService is null.
DebuggingStepTests class constructor
private readonly IDebuggingService debuggingService;
public string StepName { get; set; }
public DebuggingStep(IDebuggingService _debuggingService)
{
_log.Starting();
StepName = "DebuggingStep";
debuggingService = _debuggingService
?? throw new ArgumentException("DebuggingStep init failure due to => IDebuggingService null");
}
UnitTests looks like this
[Fact]
public void TestDebuggingStepConstructorWhen_InitServiceIsNull_ResultArgumentException()
{
//Arrange
var arrange = new Action(() =>
{
new DebuggingStep(null);
});
//Act
//Arrange
Assert.Throws<ArgumentException>(arrange);
}
And actual result:
Hope this will be helpful for somebody