簡體   English   中英

如何在單元測試中將文件添加到 object?

[英]How to handle adding a file to an object in a unit test?

我正在嘗試為在 C# 中發送 email 的方法編寫一個 nunit 單元測試。 在正在測試的方法中,會創建一個附件列表 (System.Net.Mail.Attachment),然后將項目添加到其中。

List<Attachment> emailAttachments = new List<Attachment>();
...
emailAttachments.Add(new Attachment(file));

在我的單元測試中,我不知道如何模擬 emailAttachments.Add(new Attachment(file))。 或者,如果它甚至是可能的。 當前單元測試在到達此行時失敗,因為“文件”不存在。 我是否創建一個測試文件並將其保存在項目中並使用/引用它? 還是有更好的方法來解決它?

TIA

我假設您使用System.Net.Mail來處理帶有 smtp 客戶端的消息。 如果是這樣,它將 go 像這樣

var smtp = new SmtpClient{
 // smtp configurations here (host, port, ssl) etc
};

var message = new MailMessage(){
 // message configuration here (from, body, subj) etc
};

// and this is where you should be attaching the files based on extension or whatever way you are getting all your file paths. If its just one then ignore the loop and just pass in the file path 

var filePaths =  Directory.GetFiles(@"c:\mydirectory",".", SearchOption.AllDirectories)
                      .Where(f => f.EndsWith(".extension"));

foreach(var file in filePaths){
message.Attachments.Add(new Attachment(file));
}

smtp.Send(message);
smtp?.Dispose();

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM