我有一个应用程序可以向打印机发送许多PDF文件。有没有人有过创建代表本地打印机的Mock对象的经验?
答案 0 :(得分: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 :(得分:0)
您可以随时暂停打印机进行打印。
您可以使用写入文件的打印机设备。
您可以编写自己的打印设备。
答案 2 :(得分:0)
另一个解决方案是为自己编写一个LPD应用程序或只是监控端口9100并使用Windows打印队列将数据路由到9100或515(LPD)上的“本身”。