tags:

views:

139

answers:

3

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?

A: 

You can always pause the printer for printing.

You can use a printer device that writes to a file.

And you can write your own printing device.

Paulo Santos
+9  A: 

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.

BengtBe
That's how I would do it +1
Daok
A: 

Another solution is to write yourself an LPD app or simply monitor port 9100 and have a Windows print queue route the data to 'itself' over 9100 or 515 (LPD).

Douglas Anderson