gpt4 book ai didi

c# - 使用 Nunit TestCaseSource 运行测试设置的正确方法

转载 作者:太空狗 更新时间:2023-10-30 01:01:15 28 4
gpt4 key购买 nike

我正在尝试使用 NUnit 中的 TestCaseSource 运行多个测试。但是我很难让 [SetUp] 在我需要的时候运行。

目前它按照我想要的方式工作,但感觉不“正确”。所以下面是主要的测试用例代码(简化):

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;
}

}

这里的问题是 [SetUp] 在 ImportTestCases "TestCases"之前没有运行属性“get”被运行。 “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;
}

}

如您所见,这确保了设置在返回变量之前已经运行。遗憾的是,这是迄今为止我设法让它工作的唯一方法。正如我所说,这感觉“错误”并且过于复杂。也许我在这里过度使用了测试用例?或者我应该使用某种参数化测试用例(这可能吗?)。

我已尝试简化上面的代码,如果我尝试测试的代码完全没有意义,我深表歉意。

要点是否有在创建 TestCaseSource 之前运行的 [Setup]?

最佳答案

要点是测试用例将在加载测试时定位。因此,具有 [TestFixtureSetUp] 属性的例程将在调用“TestCases”属性后执行。但是,您可以在静态构造函数中执行一些设置例程。但是为了首先调用它,您需要将测试数据放在同一个类中:

[TestFixture]
public class ImportTests
{
static ImportTests()
{
//Step 1
//run your set-up routine
}

//Step 3
[Test, TestCaseSource(nameof(ImportTests.TestCases))]
public bool PropertyTest(string s) => string.IsNullOrEmpty(s);

//Step 2
public static IEnumerable TestCases => new[] {new TestCaseData("").Returns(true)};
}

关于c# - 使用 Nunit TestCaseSource 运行测试设置的正确方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40505717/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com