我可以使用最小起订量来模拟未来的实例吗?
Can I use MOQ to mock future instances?
我是单元测试的新手,想了解更多有关最小起订量的信息。
是否有 API 允许我模拟某种类型的未来实例?
我是说,
假设我在嘲笑 class。在 class 中,我使用 new 运算符创建对象的新实例。
我想模拟将来在 class 中创建的同一类型对象的所有未来实例,有这样的 API 吗?
我试图查看最小起订量文档,但没有这样的示例。帮助任何人?
不要使用 new
,使用依赖注入和工厂。然后你可以让你的 class 创建模拟:
internal class SubjectUnderTest
{
public SubjectUnderTest( IProductFactory factory )
{
_factory = factory;
}
public void DoStuff()
{
var product = _factory.CreateProduct(); // this creates a mocked product (where you new'ed something before)
product.DoSomeThing(); // this calls into the mock product
}
private readonly IProductFactory _factory;
}
测试将如下所示
var mockFactory = new Mock<IProductFactory>();
mockFactory.Setup( x => x.CreateProduct() ).Returns( () =>
{
var mockProduct = new Mock<IProduct>();
// TODO setup product mock here
return mockProduct.Object;
} );
var instance = new SubjectUnderTest( mockFactory.Object );
instance.DoStuff(); // <- uses the factory mock defined above to create a mocked product and calls into the mocked product
我是单元测试的新手,想了解更多有关最小起订量的信息。
是否有 API 允许我模拟某种类型的未来实例?
我是说,
假设我在嘲笑 class。在 class 中,我使用 new 运算符创建对象的新实例。
我想模拟将来在 class 中创建的同一类型对象的所有未来实例,有这样的 API 吗?
我试图查看最小起订量文档,但没有这样的示例。帮助任何人?
不要使用 new
,使用依赖注入和工厂。然后你可以让你的 class 创建模拟:
internal class SubjectUnderTest
{
public SubjectUnderTest( IProductFactory factory )
{
_factory = factory;
}
public void DoStuff()
{
var product = _factory.CreateProduct(); // this creates a mocked product (where you new'ed something before)
product.DoSomeThing(); // this calls into the mock product
}
private readonly IProductFactory _factory;
}
测试将如下所示
var mockFactory = new Mock<IProductFactory>();
mockFactory.Setup( x => x.CreateProduct() ).Returns( () =>
{
var mockProduct = new Mock<IProduct>();
// TODO setup product mock here
return mockProduct.Object;
} );
var instance = new SubjectUnderTest( mockFactory.Object );
instance.DoStuff(); // <- uses the factory mock defined above to create a mocked product and calls into the mocked product