我想在NUnit中使用TestCaseSource運行多個測試。但我很努力讓[SetUp]在我需要時運行。正確的方式運行測試設置與Nunit TestCaseSource
目前它的工作方式我想要它,但它不覺得「正確」。所以,下面是主要的測試案例代碼(簡體):
public class ImportTestCases
{
ImportTestCases()
{
TestData.RunTestSetup();
}
public static IEnumerable TestCases
{
get
{
//run the funciton under test...
var results = RunFunctionSubjectToTest(TestData.ImportantVar);
//get multiple results...
var allProperties =new TestCaseData(o).Returns(true)
ExpandNestedProperties(results.AllProperties)
.ToList()
.ConvertAll(o => new TestCaseData(o).Returns(true));
return allProperties;
}
}
}
[TestFixture]
public class ImportTests
{
[TestFixtureSetUp]
public void ImporTestSetup()
{
TestData.RunTestSetup();
}
[Test, TestCaseSource(typeof(ImportTestCases), nameof(ImportTestCases.TestCases))]
public bool PropertyTest(UnitTestHelper.PropInfo info)
{
return info.DoTheyMatch;
}
}
這裏的問題是,[設置]之前沒有ImportTestCases「的TestCase」 財產「得到」的跑了跑。 「ImportTestCases」的構造函數也沒有運行。所以,爲了保證ImportVar引用之前,我需要做下面的「RunTestSetup」是跑:
public static class TestData
{
private static bool HasSetUpRan = false;
private static int _importantVar;
public static int ImportantVar
{
get
{
if(!HasSetUpRan)
{
RunTestSetup();
}
return _importantVar;
}
}
public static void RunTestSetup()
{
if (HasSetUpRan)
{
return;
}
///do set up
//e.g. _importantVar = GenerateId();
//end
HasSetUpRan= true;
}
}
正如你可以看到這保證了成立以來跑返回變量之前。可悲的是,這是我成功實現目標的唯一途徑。正如我所說的那樣,感覺「錯誤」並且過於複雜。也許我在這裏過度使用測試用具?或者我應該使用某種形式化的測試用例(可能嗎?)。
我試圖簡化上面的代碼,所以道歉,如果它根本沒有意義,我試圖測試。
主要點是否有一個[Setup]在TestCaseSources創建之前運行?
這絕對解決了這個問題,而不需要布爾的東西:)。我會試着理解Charlies回答多一點,看看我是否做錯了:) – chrispepper1989