如何在.NET中模拟打印机?

Cod*_*y C 5 .net mocking

我有一个应用程序,可以发送许多PDF到打印机.有没有人有任何创建代表本地打印机的Mock对象的经验?

Ben*_*tBe 12

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

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

interface IPrinter 
{
   void Print(PrintData data);
}
Run Code Online (Sandbox Code Playgroud)

然后,所有其他代码必须通过此界面与打印机通信.

然后,您可以实现与真实打印机对话的此接口的一个版本,以及在测试时可以使用的一个假对象.

使用像Rhino MocksMoq这样的模拟框架可以很容易地模拟假对象,或者你可以自己实现伪造的对象.

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

更新:

所有使用打印机的类将看起来像这样:

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)
   }
}
Run Code Online (Sandbox Code Playgroud)

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