问题描述:

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.

网友答案:

Your unit tests should not be dependent on other unit tests.

The function marked with [Setup] will be called before every [Test] function in your class. So if you move the _dataField creation to [Setup], it will continually recreate it. Is that what you are unsure of?

A function marked with [TestFixtureSetUp] will be called once at the start of a [TestFixure]. So it wont be called before every [Test]

[SetUp]
public void TestSetup()
{
   _dataField =  new DataField(dependency1, dependency2, dependency3);
}

[Test]
public void DataField_Gets_Properly_Created()
{
    Assert.NotNull(dataField.Id);
    // other assertions ...
}

[Test]
public void Most_Test_Using_dataField()
{
    ...
}

Here the first test will fail if its not 'initialized' properly. In this case, you'll know there is a problem and cant guarantee other Tests will work.

相关阅读:
Top