关于单元测试,若是不会用能够参照个人上篇博文————在Visual Studio 2012使用单元测试html
首先分享一篇博文,[Visual Studio] 开启Visual Studio 2012经过右键菜单建立单元测试(Unit Test)。 ide
泛型有两种,通常泛型与类型约束泛型,在对包含泛型的方法进行单元测试中也能够这么分,详情可参阅http://msdn.microsoft.com/en-us/library/vstudio/ms243401.aspx 。从该页面能够知道,关于泛型的单元测试,微软类库(Microsoft.VisualStudio.TestTools.UnitTesting)提供了类“GenericParameterHelper”帮助咱们编写Unit Test代码。post
首先看下非类型约束的一个demo,我就直接上代码了单元测试
public static bool IsCollectionEmpty<T>(ICollection<T> collection) { return collection == null || collection.Count < 1; }
测试代码测试
/// <summary> ///IsCollectionEmpty 的测试 ///</summary> public void IsCollectionEmptyTestHelper<T>() { //三个用例:以非空集合,空集合,null分别做为参数 ICollection<T> collection = new T[]{default(T)}; // TODO: 初始化为适当的值 bool expected = false; // TODO: 初始化为适当的值 bool actual; actual = UtilityCheckData.IsCollectionEmpty<T>(collection); Assert.AreEqual(expected, actual); collection = new T[] { }; Assert.AreEqual(true, UtilityCheckData.IsCollectionEmpty<T>(collection)); Assert.AreEqual(true, UtilityCheckData.IsCollectionEmpty<T>(null)); } [TestMethod()] public void IsCollectionEmptyTest() { IsCollectionEmptyTestHelper<GenericParameterHelper>(); }
关于泛型的测试其实也挺简单的,没什么能够啰嗦的,可是若是有了类型约束,那么GenericParameterHelper类将极可能再也不能用了。this
而后再来看我作的一个类型约束泛型的单元测试代码。url
写一个相似栈的需测试的类:spa
public class StackNum<T> where T : struct { List<T> array = null; public StackNum() { this.array = new List<T>(); } public void Push(T value) { array.Add(value); } public T Pop() { T val = array[this.Length - 1]; this.array.Remove(val); return val; } public int Length { get { return this.array.Count; } } }
在测试项目编写一个测试帮助类code
class StackTestHelper { public static void LengthTest<T>() where T : struct { var stack = GetStackInstance<T>(); Assert.AreEqual(stack.Length, 0); } public static void PushTest<T>() where T : struct { var stack = GetStackInstance<T>(); stack.Push(default(T)); Assert.AreEqual(stack.Length, 1); } public static void PopTest<T>(params T[] values) where T : struct { var stack = GetStackInstance<T>(); if (values == null) { return; } int pushLength = 0; foreach (T val in values) { stack.Push(val); Assert.AreEqual(stack.Length, ++pushLength); } for (int i = stack.Length - 1; i >= 0; i--) { Assert.AreEqual<T>(stack.Pop(), values[i]); Assert.AreEqual(stack.Length, i); } } public static StackNum<T> GetStackInstance<T>() where T : struct { return new StackNum<T>(); } }
测试类htm
[TestClass] public class StackTest { [TestMethod] public void PushTest() { StackTestHelper.PushTest<decimal>(); StackTestHelper.PushTest<double>(); } [TestMethod] public void PopTest() { StackTestHelper.PopTest<int>(22, 33, 55); StackTestHelper.PopTest<bool>(true, false); } [TestMethod] public void LengthTest() { StackTestHelper.LengthTest<char>(); } }
这么写单元测试能够简单的切换咱们所须要进行测试的各类类型。
总结:对泛型作单元测试时相对会比通常的测试多写一些代码,不过多进行些抽象封装仍是彻底能够接受的,目前还不知道有什么更好的办法,如您有更好的办法,请赐教,草民将不尽感激!!
题外话:感受我编写单元测试的代码比我编写知足功能需求的代码还多,可是我对着玩意儿却丝毫没任何抵触情绪,但愿刚开始步入Unit Test的你也是。