Unit testing 用假动作伪造SUT的内部呼叫
我有一个处理打印的小C#类。 我想为这个类创建(n)个单元测试,使用 假惺惺的。我怎么能伪造这个公司的内部电话 上课的时候不假装整件事 例如:Unit testing 用假动作伪造SUT的内部呼叫,unit-testing,nunit,fakeiteasy,Unit Testing,Nunit,Fakeiteasy,我有一个处理打印的小C#类。 我想为这个类创建(n)个单元测试,使用 假惺惺的。我怎么能伪造这个公司的内部电话 上课的时候不假装整件事 例如: public class MyPrintHandler: IMyPrintHandler { public MyPrintHandler(ILogger<MyPrintHandler> logger) { } // function I want to (unit test pu
public class MyPrintHandler: IMyPrintHandler
{
public MyPrintHandler(ILogger<MyPrintHandler> logger)
{
}
// function I want to (unit test
public async Task<bool> PrintAsync(string ipaddress)
{
try
{
if (!string.IsNullOrWhiteSpace(ipaddress) )
{
return await StartPrint(ipaddress); // This cannot be called in a unit test, because it really start printing on a printer.
}
}
catch (Exception e)
{
}
return false;
}
private async Task<bool> StartPrint(string ipaddress)
{
// prints on the printer
}
[TestFixture]
public class MyPrintHandlerTests
{
[Test]
public void Succes_PrintAsync()
{
using (var fake = new AutoFake())
{
// Arrange - configure the fake
var sut = fake.Resolve<MyPrintHandler>();
// Act
await sut.PrintAsync("0.0.0.0"); // I want to prevent StartPrint() from being called..
}
}
}
公共类MyPrintHandler:IMyPrintHandler
{
公共MyPrintHandler(ILogger记录器)
{
}
//我想要的函数(单元测试)
公共异步任务PrintAsync(字符串ipaddress)
{
尝试
{
如果(!string.IsNullOrWhiteSpace(ipaddress))
{
return await StartPrint(ipaddress);//在单元测试中不能调用此函数,因为它确实开始在打印机上打印。
}
}
捕获(例外e)
{
}
返回false;
}
专用异步任务StartPrint(字符串ipaddress)
{
//在打印机上打印
}
[测试夹具]
公共类MyPrintHandlerTests
{
[测试]
public void success_PrintAsync()
{
使用(var fake=new AutoFake())
{
//安排-配置假文件
var sut=false.Resolve();
//表演
wait sut.PrintAsync(“0.0.0.0”);//我想阻止调用StartPrint()。。
}
}
}
我如何才能做到这一点,或者这根本不可能?
谢谢,提前。 我通常会说冒充SUT是一种反模式,只要可能,就要避免,因为它会引起混淆。如果你可以重构来介绍一个处理<代码> StestPrime<代码>方法的合作者,我会强烈地考虑这样做。如果这是不可能的,你可以试试这个,但是
虚拟的
或抽象的
,否则FakeiTesy无法拦截它公共的
(或者内部的
,如果可以的话,可以复制到生产代码的内部)谢谢你的回答和其他的步骤。我选择了重构和使用适配器。但是如果有必要的话,知道我可以采取什么步骤是很好的