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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With