简体   繁体   English

如何在.NET中打印到空打印机?

[英]How to print to a null printer in .NET?

I need to write a unit test for a method that will print a document. 我需要为打印文档的方法编写单元测试。 Is there an easy way to send the output to the Windows equivalent of /dev/null? 有没有一种简单的方法将输出发送到Windows等效的/ dev / null? I'm guessing that having our build server print a document on every check in is going to get expensive quickly. 我猜测让我们的构建服务器在每次签入时打印文档都会很快变得昂贵。 ;) ;)

Ideally, this would work on both our build server (which has no default printer) and our development machines (which do), so I'd prefer not to change the default printer. 理想情况下,这可以在我们的构建服务器(没有默认打印机)和我们的开发机器(这样做)上工作,所以我不想更改默认打印机。

Thanks for all the wonderful answers that will undoubtedly follow this fascinating question. 感谢所有精彩的答案,无疑将遵循这个引人入胜的问题。

I do this by creating a Windows printer that prints to the NUL device. 我这样做是通过创建一个打印到NUL设备的Windows打印机。 This is pretty straightforward though the specifics differ a bit between Windows versions: just create a local printer and specify NUL as the local port, "Generic" as the Manufacturer and "Generic / Text Only" as the printer model. 虽然Windows版本之间的细节略有不同,但这非常简单:只需创建本地打印机并指定NUL作为本地端口,将“Generic”指定为制造商,将“Generic / Text Only”指定为打印机型号。

You should use a mocking framework to mock out the print method so that it is never actually executed. 您应该使用模拟框架来模拟print方法,以便它永远不会被实际执行。

Check out TypeMock or RhinoMocks for something that will help you do this. 查看TypeMock或RhinoMocks可以帮助您完成此任务。

This is how it would look using TypeMock: 这是使用TypeMock的外观:

Mock mock = MockManager.Mock<PrintManager>();
mock.ExpectCall("Print");

Then you would execute the code in your test that inside it calls this method. 然后,您将在测试中执行代码,在其中调用此方法。 This will then intercept the print call and the document will not be sent to the printer but you can still unit test the business logic around the time of print. 然后,这将拦截打印调用,文档将不会发送到打印机,但您仍然可以在打印时单元测试业务逻辑。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM