C# 如何对调用其他WCF的WCF服务进行单元测试
我已经设置了2个wcf服务,它们是 PdfService.svc 和 MailService.svc 邮件服务附加由PDFService ie生成的PDFC# 如何对调用其他WCF的WCF服务进行单元测试,c#,wcf,C#,Wcf,我已经设置了2个wcf服务,它们是 PdfService.svc 和 MailService.svc 邮件服务附加由PDFService ie生成的PDF public void SendMail(ICommand command) { // how should I handle this in Unit Test (mocks with NSubstitute) _service = new PdfService(_pdfSettings);
public void SendMail(ICommand command)
{
// how should I handle this in Unit Test (mocks with NSubstitute)
_service = new PdfService(_pdfSettings);
var request = new DownloadRequest {FileName = "form.pdf",
FormEntry = command.FormEntry };
var thefile = _service.DownloadFile(request);
sendEmail(command.Mail, thefile.FileByteStream);
}
我想知道如何在测试邮件服务时删除PdfService,这对于将wcf与wcf通信是个坏主意吗
谢谢 您可能想使用和
一般的想法是在方法调用或对象构造函数中将服务传递给方法。根据您提供的代码片段,我将按以下方式重写:
//Method Call
IPdfService mockService = new MockPdfService() // this is a mock that implements your interface
SendMail(cmd, mockService);
//Method
public void SendMail(ICommand command, IPdfService service)
{
// how should I handle this in Unit Test (mocks with NSubstitute)
_service = new PdfService(_pdfSettings);
var request = new DownloadRequest {FileName = "form.pdf",
FormEntry = command.FormEntry };
var thefile = service.DownloadFile(request);
sendEmail(command.Mail, thefile.FileByteStream);
}
在mockService中,您可以添加诊断帮助,然后在sendmail调用后编写断言,以查看模拟中发生的情况
也许更好的方法是让主类构造函数获取服务对象,然后重写方法调用,如下所示:
public class MyClass
{
private IPdfService _pdfService;
public MyClass()
{
_pdfService = new PdfService(_pdfSettings);
}
// Call this with your Mock pdfService
public MyClass(IPdfService pdfService)
{
_pdfService = pdfSerivce;
}
public void SendMail(ICommand command)
{
var request = new DownloadRequest { FileName = "form.pdf", FormEntry = command.FormEntry };
var thefile = _pdfService.DownloadFile(request);
sendEmail(command.Mail, thefile.FileByteStream)
}
}
您可能已经考虑过这一点——单独编写单元测试,并相互进行模拟怎么样。是的,编写包含这两种服务的集成单元测试是很棘手的。邮件服务实现需要一个DI构造函数,该构造函数接受pdf服务的接口,这将允许您在测试期间通过存根实现。