在单元测试的程序集中,找到需要测试的程序集引用,右键添加Fakes程序集,即可。
一、底层类和接口的
public interface ICity
{
int GetCityDal();
}
public class City : ICity
{
public int GetCityDal()
{
return 85;
}
}
二、调用City类的类,即被测试类
public class HomeController : Controller
{
ICity _city = null;
public HomeController()
{
}
public HomeController(ICity city)
{
_city = city;
}
public ActionResult Index()
{
return Content("0");
}
public int GetCity()
{
City c = new City();
int ac = c.GetCityDal();
return ac + 1;
}
public int GetCityIOC()
{
int ac = _city.GetCityDal();
return ac + 1;
}
public static bool IsDouble()
{
if (DateTime.Now.Day % 2 == 0)
{
return true;
}
else
{
return false;
}
}
}
三、编写的单元测试类
[TestClass]
public class HomeControllerTest
{
[TestMethod]
public void IndexTest()
{
HomeController hc = new HomeController();
ContentResult vr = hc.Index() as ContentResult;
Assert.AreEqual(vr.Content, "0");
}
//强依赖性
[TestMethod]
public void GetCityTest()
{
//尽量不要出现此单元测试
int r = 0;
using (ShimsContext.Create())
{
ShimCity.AllInstances.GetCityDal = (@this) =>
{
return 10;
};
HomeController hc = new HomeController();
r = hc.GetCity();
}
Assert.AreEqual(r, 11);
}
//弱依赖性
[TestMethod]
public void GetCityIOCTest()
{
ICity city = new StubICity()
{
GetCityDal = () =>
{
return 20;
}
};
HomeController hc = new HomeController(city);
int r = hc.GetCityIOC();
Assert.AreEqual(r, 21);
}
//静态类测试
[TestMethod]
public void IsDoubleTest()
{
bool temp = false;
using (ShimsContext.Create())
{
ShimDateTime.NowGet = () => new DateTime(2017, 3, 28);
temp = HomeController.IsDouble();
}
Assert.IsTrue(temp);
}
}