如何模拟在单元测试的函数内使用的SmtpClient对象

时间:2017-11-16 03:46:43

标签: c# unit-testing mocking nunit moq

我想为BatchProcess中的SendMail方法编写Nunit或单元测试,而不发送邮件。

如何模拟另一个方法中存在的SmtpClient。请帮忙。

ftp = FTP('REDACTED')  
ftp.login('REDACTED', 'REDACTED')
print ("Opening FTP...\n")
   with open ('REDACTED.gz.uboot') as f: 
    print ('writing file...REDACTED.gz.uboot') 
    ftp.storbinary('STOR %s' % 'REDACTED.gz.uboot', f)

with open('REDACTED_Image', 'rb') as x:
    print ("writing file...REDACTED_Image")
    ftp.storbinary('STOR %s' % 'Image', f)

with open('REDACTED.rbf', 'rb') as f:  
    ftp.storbinary('STOR %s' % 'huh.rbf', f)
    print ("writing file...m0_host_top.rbf")

with open ('REDACTED.tar.bz2') as f:
    print ('writing file...REDACTED')
    ftp.storbinary('STOR %s' % 'REDACTED', f)

with open ('REDACTED.bin') as f:
    print ('writing file...REDACTED.bin')
    ftp.storbinary('STOR %s' % 'REDACTED.bin', f)

1 个答案:

答案 0 :(得分:3)

这就是你应该使用Dependency Injection的原因之一。

关键是您不应在Console output /*--- Destination array - arrayOneValue[0] arrayOneValue[1] arrayOneValue[2] arrayOneValue[3] arrayOneValue[4] arrayTwoValue[0] arrayTwoValue[1] arrayTwoValue[2] arrayTwoValue[3] arrayTwoValue[4] arrayTwoValue[5] arrayThreeValue[0] arrayThreeValue[1] arrayThreeValue[2]*/ 中创建SmtpClient的实例。最好在SendMail()上定义实现SmtpClient接口的包装器,并将该接口传递给ISmtpClient的构造函数,以便在测试中模拟它:

BatchProcess