[英]Unit Test for Generic function in C#
似乎是一个很普遍的问题,但我还没有找到答案,所以
简而言之,我有一个通用功能需要对它执行unit test
,例如
public void T[] DoSomething<T>(T input1, T input2)
现在,我需要测试此函数是否对int,ArrayList有效,在这种情况下如何编写单元测试,列出T的所有情况都不是一种选择,我想到的只是测试int和某些类实例?
我也尝试使用VS2012自动生成的单元测试,如下所示:
public void DoSomethingHelper<T>() {
T item1 = default(T);; // TODO: Initialize to an appropriate value
T item2 = default(T); // TODO: Initialize to an appropriate value
T[] expected = null; // TODO: Initialize to an appropriate value
T[] actual = SomeClass.DoSomething<T>(item1, item2);
Assert.AreEqual(expected, actual);
Assert.Inconclusive("Verify the correctness of this test method.");
}
[TestMethod()]
public void AddTest() {
AddTestHelper<GenericParameterHelper>();
}
这让我更加困惑,我应该在DoSomethingHelper中放入什么来初始化变量? 整数,字符串或其他东西?
有人可以帮忙吗? 我听说过Pex和其他产品,但仍然没有人为我提供此简单功能的示例单元测试代码。
您可能需要检查NUnit的通用测试装置 ,以使用T
多个实现进行测试
首先,请考虑以下几点: 为什么要创建泛型函数?
如果您正在编写通用函数/方法,则不必在意所使用类型的实现。 我的意思是,只不过是您在通用类中指定的内容(例如, where T : IComparable<T>, new()
等)
因此,我的建议是创建一个适合通用类型要求的虚拟类,并对其进行测试。 使用NUnit
的示例:
class Sample {
//code here that will meet the requirements of T
//(eg. implement IComparable<T>, etc.)
}
[TestFixture]
class Tests {
[Test]
public void DoSomething() {
var sample1 = new Sample();
var sample2 = new Sample();
Sample[] result = DoSomething<Sample>(sample1, sample2);
Assert.AreEqual(2, result.Length);
Assert.AreEqual(result[0], sample1);
Assert.AreEqual(result[1], sample2);
}
}
编辑:考虑一下,您将看到它起作用。 您可能会想:“ 好吧,但是如果DoSomething
的主体具有类似...的含义,该怎么办? ”:
if (item1 is int) {
//do something silly here...
}
当然,在使用int
进行测试时它将失败,并且由于正在使用Sample
类进行测试,因此您不会注意到它,但是可以认为它就像您正在测试一个将两个数字相加的函数一样,并且您将遇到以下情况:
if (x == 18374) {
//do something silly here...
}
您也不会识别它。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.