.net freamwork 4.5 shim type最新Unit框架
建立新的控制台工程,代码如下:
Class1:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApplication1
{
public class Class1
{
public int AddMethod(int a, int b)
{
return a + b;
}
public DateTime GetTime()
{
return new DateTime(2000, 1, 1);
}
public static string GetHello()
{
return "hello world";
}
public string GetInsertMethod()
{
return new Class3().InsertMethod();
}
}
}
Class2:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApplication1
{
public static class Class2
{
public static string GetString()
{
return "hello world";
}
}
}
Class3:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApplication1
{
public class Class3
{
public string InsertMethod()
{
return "insert method";
}
}
}
建立Test Project:
UnitTest:
using System;
using System.Fakes;
using ConsoleApplication1;
using ConsoleApplication1.Fakes;
using Microsoft.QualityTools.Testing.Fakes;
using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace UnitTestProject2
{
[TestClass]
public class UnitTest1
{
[TestMethod]
public void TestStaticDate()
{
using (ShimsContext.Create())
{
// to return January 1st of 2000
ShimDateTime.NowGet = () => new DateTime(2000, 1, 1);
Assert.AreEqual(new Class1().GetTime(), DateTime.Now);
}
}
[TestMethod]
public void TestStaticClass()
{
using (ShimsContext.Create())
{
ShimClass2.GetString = () => "Jason";
Assert.AreEqual(Class2.GetString(), "Jason");
}
}
[TestMethod]
public void TestStaticMethod()
{
using (ShimsContext.Create())
{
ShimClass1.GetHello = () => { return "test3"; };
Assert.AreEqual(Class1.GetHello(), "test3");
}
}
[TestMethod]
public void TestAddMethod()
{
using (ShimsContext.Create())
{
//Func<Class1, int, int, int> test =
ShimClass1.AllInstances.AddMethodInt32Int32 = (class1, b, c) =>
{
DateTime time = class1.GetTime();
return 5;
};
Assert.AreEqual(new Class1().AddMethod(1, 2), 5);
}
}
[TestMethod]
public void TestSonMethod1()
{
using (ShimsContext.Create())
{
ShimClass3.AllInstances.InsertMethod = (class3) =>
{
return "change son method...";
};
Assert.AreEqual(new Class1().GetInsertMethod(), "change son method...");
}
}
}
}
在Fake Freamwork 中,Shim type类型可以对static 和一些普通方法进行欺骗,msdn中这样描述:Shim types allow detouring of hard-coded dependencies on static or non-overridable methods
更多信息参考:Isolating Unit Test Methods with Microsoft Fakes
http://msdn.microsoft.com/en-us/library/hh549175%28v=vs.110%29.aspx