Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to Mock a printer in .NET?

Tags:

.net

mocking

I have an application that sends out many PDF's to a printer. Has anyone had any experience creating a Mock object that represents a local printer?

like image 233
Cody C Avatar asked Jun 19 '09 17:06

Cody C


1 Answers

Not entirely sure what you are trying to do, but this might help.

In order to mock a printer (or any other external device) you should encapsulate all the calls to the printer behind an interface, e.g.

interface IPrinter 
{
   void Print(PrintData data);
}

All your other code must then talk to the printer through this interface.

You can then implement one version of this interface that talks to the real printer, and one fake object that you can use when testing etc.

The fake object can easily be mocked using a mocking framework like Rhino Mocks or Moq, or you can just implement a fake one yourself.

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

Update:

All the classes that uses the printer will then look something like this:

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)
   }
}

BTW, if you uses a IoC container then you don't need the first constructor. You then inject the printer classes using the IoC tool.

like image 134
BengtBe Avatar answered Sep 21 '22 09:09

BengtBe