[英]Can I use moq Mock<MyClass> to mock a class, not an interface?
[英]Can I use MOQ to mock future instances?
我是單元測試的新手,試圖弄清楚有關MOQ的更多信息。
是否有API可讓我模擬某些類型的未來實例? 我的意思是,
假設我在嘲笑一堂課。 在該類中,我使用new運算符創建對象的新實例。
我想模擬將來將在該類中創建的該對象的同一類型的所有將來實例,是否有這樣的API?
我嘗試查看起訂量文檔,但沒有這樣的示例。 幫助任何人?
不要使用new
,而要使用依賴注入和工廠。 然后,您可以讓您的課程創建模擬:
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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.