.net freamwork 4.5 stub type最新Unit Test框架Fake Freamwork
新建一个控制台工程:定义以下接口和类:
1、public interface ICommonMethod
{
int MyMethod();
}
2、 public interface Iproperty
{
int Value { get; set; }
}
3、public interface IGenericMethod
{
T GetValue<T>();
}
4、public class virtualClass
{
public virtual string GetString()
{
return "virtual";
}
}
5、 public class Class1
{
public string GetShimString()
{
return "ShimString";
}
}
6、public class InternalClass
{
internal string GetInternalString()
{
return "internal";
}
}
在AssemblyInfo.cs文件中加入[assembly: InternalsVisibleTo("UnitTestProject1")],当然,你建立的Test project名称为:UnitTestProject1
7、 public class privateClass
{
private string GetPrivateString()
{
return "private";
}
}
以下代码,首先建立Test project 名称为:UnitTestProject1,以下为自己写的测试方法,Visual studio 2012不幸把右键自动生成测试代码的功能去掉了。
[TestMethod]
public void TestICommonMethod()
{
var stub = new StubICommonMethod();
stub.MyMethod = () => { return 3; };
Assert.AreEqual(stub.MyMethod(), 3);
}
[TestMethod]
public void TestIproperty()
{
int i = 0;
var stub = new StubIproperty();
stub.ValueGet = () => 5;
stub.ValueSetInt32 = (value) => i = value + 6;
stub.ValueSetInt32(30);
Assert.AreEqual(stub.ValueGet(), 5);
Assert.AreEqual(i, 36);
}
[TestMethod]
public void TestGenericMethod()
{
var stub = new StubIGenericMethod();
stub.GetValueOf1<string>(() => "Jason");
IGenericMethod target = stub;
Assert.AreEqual("Jason", target.GetValue<string>());
}
[TestMethod]
public void TestVirtualClass1()
{
var stub = new StubvirtualClass()
{
CallBase = false
};
stub.GetString01 = () => { return "Jason"; };
Assert.AreEqual("Jason", stub.GetString());
}
[TestMethod]
public void TestVirtualClass2()
{
var stub = new StubvirtualClass()
{
CallBase = true
};
//stub.GetString01 = () => { return "Jason"; }; stub.GetString() return "Jason"
Assert.AreEqual("virtual", stub.GetString());
}
[TestMethod]
public void MyTestMethodShimMixStub()
{
using (ShimsContext.Create())
{
var stub = new StubICommonMethod();
stub.MyMethod = () => { return 3; };
Assert.AreEqual(stub.MyMethod(), 3);
ShimClass1.AllInstances.GetShimString = (a) => { return "hello world"; };
Assert.AreEqual(new Class1().GetShimString(), "hello world");
}
}
[TestMethod]
public void TestInternalMethod()
{
using (ShimsContext.Create())
{
ShimInternalClass.AllInstances.GetInternalString = (class1) => "aaa";
Assert.AreEqual(new InternalClass().GetInternalString(), "aaa");
}
}
[TestMethod]
public void TestPrivateMethod()
{
using (ShimsContext.Create())
{
ShimprivateClass.AllInstances.GetPrivateString = (class1) => "aaa";
//Assert.AreEqual(new privateClass()...
}
}