如何将新的List< INT> {1}在NUNIT测试用例? [英] How do I put new List<int> {1} in an NUNIT TestCase?
问题描述
我的方法:
公共静态INT加入(列表< INT>数字)
{
如果(数字== NULL || numbers.Count == 0)
返回0;
如果(numbers.Count == 1)
返回号码[0];
抛出新NotImplementedException();
}
下面是我反对的测试,但它不喜欢新的List< INT> {1}
在TestCase的:
[TestCase的(新的List< INT> {1}, 1)]
公共无效Add_WithOneNumber_ReturnsNumber(列表< INT>数字)
{
VAR的结果= CalculatorLibrary.CalculatorFunctions.Add(数字);
Assert.AreEqual(1,结果);
}
这给我的错误:
的属性参数必须是常量表达式的typeof属性参数类型
的表达或数组创建表达式
我必须做的是这样的:
[测试]
公共无效Add_WithOneNumber_ReturnsNumber()
{
VAR的结果= CalculatorLibrary.CalculatorFunctions.Add(新名单< INT> {7});
Assert.AreEqual(7结果);
VAR结果2 = CalculatorLibrary.CalculatorFunctions.Add(新名单< INT> {3});
Assert.AreEqual(4,结果2);
}
有就是用一个选项 TestCaseSource 属性。在这里我提供一个非断言测试有两个分支只是为了看看它是如何工作的:
[的TestFixture]
公一流的TestClass
{
私有对象[] = _sourceLists {新的对象[] {新的List< INT> {1}} //情况1
新的对象[] {新的List< INT> {1,2}} //情况下2
};
[测试,TestCaseSource(_ sourceLists)]
公共无效测试(名单< INT>清单)
{
的foreach(在列表VAR项)
Console.WriteLine(项目);
}
}
无论如何,我不得不提到它是不是最明显解决方案,我宁愿整齐灯具忽略了一个事实,他们更详细
I have the method:
public static int Add(List<int> numbers)
{
if (numbers == null || numbers.Count == 0)
return 0;
if (numbers.Count == 1)
return numbers[0];
throw new NotImplementedException();
}
Here is my test against it, but it does not like new List<int> {1}
in the TestCase:
[TestCase(new List<int>{1}, 1)]
public void Add_WithOneNumber_ReturnsNumber(List<int> numbers)
{
var result = CalculatorLibrary.CalculatorFunctions.Add(numbers);
Assert.AreEqual(1, result);
}
It gives me the error:
An attribute argument must be a constant expression, typeof expression or array creation expression of an attribute parameter type
Do I have to do it like this:
[Test]
public void Add_WithOneNumber_ReturnsNumber()
{
var result = CalculatorLibrary.CalculatorFunctions.Add(new List<int>{7});
Assert.AreEqual(7, result);
var result2 = CalculatorLibrary.CalculatorFunctions.Add(new List<int> {3});
Assert.AreEqual(4,result2);
}
There is one option to use TestCaseSource attribute. Here I provide a non-assert test with two cases just to see how it works:
[TestFixture]
public class TestClass
{
private object[] _sourceLists = {new object[] {new List<int> {1}}, //case 1
new object[] {new List<int> {1, 2}} //case 2
};
[Test, TestCaseSource("_sourceLists")]
public void Test(List<int> list)
{
foreach (var item in list)
Console.WriteLine(item);
}
}
Anyhow I have to mention it is not the most evident solution and I would prefer neatly organized fixtures ignoring the fact they are more verbose
这篇关于如何将新的List< INT> {1}在NUNIT测试用例?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!