我在.net框架中的MSTest2项目中使用MS Fake框架来模拟静态成员,例如
System.DateTime.Now
是否有相同的框架可以像dotnet core 2.0中的Fake一样做什么?
答案 0 :(得分:-2)
首先让我告诉你不能模拟DateTime.Now,因为'Now'是一个静态属性。模拟的主要思想是解除依赖关系,并且应该将依赖注入相应的classess来模拟它。这意味着你必须实现dependend类的接口,并且接口应该注入消耗依赖类的类。对于单元测试,模拟相同的接口。所以接口永远不适合Static,因为接口总是期望一个concreate类类型,你必须实例化实现相同接口的类。
话虽如此,如果你使用MSTest,还有一个名为Shim的概念(虽然我不是Shim的忠实粉丝)。你可以创建假装配。在您的情况下,您可以创建'System'和Fake DateTime的伪装配,如下所示,
[TestMethod]
public void TestCurrentYear()
{
int fixedYear = 2000;
// Shims can be used only in a ShimsContext:
using (ShimsContext.Create())
{
// Arrange:
// Shim DateTime.Now to return a fixed date:
System.Fakes.ShimDateTime.NowGet =
() =>
{ return new DateTime(fixedYear, 1, 1); };
// Instantiate the component under test:
var componentUnderTest = new MyComponent();
// Act:
int year = componentUnderTest.GetTheCurrentYear();
// Assert:
// This will always be true if the component is working:
Assert.AreEqual(fixedYear, year);
}
}
要Shim或创建假装配,您需要视觉工作室终极及以上。
请阅读有关垫片here
的更多信息