I’m testing a class, which has pretty much dependencies from other classes. To solve this I use mocks. That worked very well so far.
[Test]
public void DataField_Gets_Properly_Created()
{
// Arrange all those mocks
_dataField = new DataField(dependency1, dependency2, dependency3);
Assert.NotNull(dataField.Id);
// other assertions ...
}
[Test]
public void DataField_Gets_Properly_Saved()
{
var entityList = new List<IEntity>();
var dfId = Guid.NewGuid();
_dataField.SetValue(true, entityList, dfId);
Assert.True(_datenFeld.ValueBoolean);
// other assertions
}
As you can see I use this private _dataField variable. You know, I actually test if a data field can be created in the first test. Is it a bad approach to use the same data field in the second test, which just got created in the first method? I think this isn’t very clean code.
The second idea I’ve had was creating this data field in the [Setup]. This isn’t very clean either, because how should I create it in the setup and test afterwards if it even can be created? I’m confused.
Afterwards could be even more tests which all need an instance of a data field to test the actual class DataField.
A unit test should not depend on any other unit tests. You should be able to run each one individually and have them pass, and you should be able to run them in any arbitrary order.
In this case, I’d recommend using a local variable that you re-initialize in each test, but arrange all the mocks in the
[Setup]. You can encapsulate the initialization in a helper method,CreateDataFieldForTest()or similar.