NUnit TestCaseSource 将值传递给工厂 [英] NUnit TestCaseSource pass value to factory
问题描述
我正在使用 NUnit 2.5.3 TestCaseSource 属性并创建一个工厂来生成我的测试.像这样:
I'm using the NUnit 2.5.3 TestCaseSource attribute and creating a factory to generate my tests. Something like this:
[Test, TestCaseSource(typeof(TestCaseFactories), "VariableString")]
public void Does_Pass_Standard_Description_Tests(string text)
{
Item obj = new Item();
obj.Description = text;
}
我的来源是这样的:
public static IEnumerable<TestCaseData> VariableString
{
get
{
yield return new TestCaseData(string.Empty).Throws(typeof(PreconditionException))
.SetName("Does_Reject_Empty_Text");
yield return new TestCaseData(null).Throws(typeof(PreconditionException))
.SetName("Does_Reject_Null_Text");
yield return new TestCaseData(" ").Throws(typeof(PreconditionException))
.SetName("Does_Reject_Whitespace_Text");
}
}
我需要做的是向变量字符串添加一个最大长度检查,但是这个最大长度是在被测类的契约中定义的.在我们的例子中,它是一个简单的公共结构:
What I need to be able to do is to add a maximum length check to the Variable String, but this maximum length is defined in the contracts in the class under test. In our case its a simple public struct:
public struct ItemLengths
{
public const int Description = 255;
}
我找不到任何将值传递给测试用例生成器的方法.我已经尝试过静态共享值,但这些值没有被采用.我不想将内容保存到文件中,因为每次更改代码时我都需要重新生成此文件.
I can't find any way of passing a value to the test case generator. I've tried static shared values and these are not picked up. I don't want to save stuff to a file, as then I'd need to regenerate this file every time the code changed.
我想将以下行添加到我的测试用例中:
I want to add the following line to my testcase:
yield return new TestCaseData(new string('A', MAX_LENGTH_HERE + 1))
.Throws(typeof(PreconditionException));
概念上相当简单的事情,但我发现不可能做到的事情.有什么建议吗?
Something fairly simple in concept, but something I'm finding impossible to do. Any suggestions?
推荐答案
将测试的参数更改为类而不是字符串.像这样:
Change the parameter of your test as class instead of a string. Like so:
公共类 StringTest {公共字符串 testString;公共 int maxLength;}
public class StringTest { public string testString; public int maxLength; }
然后构造这个类作为参数传递给 TestCaseData 构造函数.这样你就可以传递字符串和你喜欢的任何其他参数.
Then construct this class to pass as an argument to TestCaseData constructor. That way you can pass the string and any other arguments you like.
另一种选择是让测试有 2 个 string 和 int 参数.
Another option is to make the test have 2 arguments of string and int.
然后是 TestCaseData("mystring", 255).您是否意识到它们可以有多个参数?
Then for the TestCaseData( "mystring", 255). Did you realize they can have multiple arguments?
韦恩
这篇关于NUnit TestCaseSource 将值传递给工厂的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!