2009-06-19 92 views

回答

12

不完全确定你想要做什么,但这可能有帮助。

为了模拟打印机(或任何其他外部设备),您应该将所有对打印机的调用封装在一个接口后面,例如,

interface IPrinter 
{ 
    void Print(PrintData data); 
} 

所有其他代码必须通过此接口与打印机通信。

然后,您可以实现此接口,讨论到实际打印机的一个版本,一个假的对象用讽刺的框架像Rhino Mocks或测试时等

假冒的对象可以很容易地嘲笑,你可以使用Moq,或者你可以自己实施一个假的。

public class FakePrinter : IPrinter 
{ 
    public void Print(PrintData data) 
    { 
     // Write to output window or something 
    } 
} 

更新:使用打印机,然后就会是这个样子

所有类:

public class ClassThatPrints 
{ 
    private IPrinter _Printer; 

    // Constructor used in production 
    public ClassThatPrints() : this(new RealPrinter()) 
    { 
    } 

    // Constructor used when testing 
    public ClassThatPrints(IPrinter printer) 
    { 
     _Printer = printer; 
    } 

    public void MethodThatPrints() 
    { 
     ... 
     _Printer.Print(printData) 
    } 
} 

顺便说一句,如果你使用IoC容器,那么你就不需要第一个构造函数。然后使用IoC工具注入打印机类。

+1

我就是这样做的+1 +1 – 2009-06-19 17:37:28

0

您可以随时暂停打印机进行打印。

您可以使用写入文件的打印机设备。

而且您可以编写自己的打印设备。

0

另一种解决方案是自己编写一个LPD应用程序或者只是监视端口9100,并让Windows打印队列通过9100或515(LPD)将数据路由到“自己”。