简体   繁体   中英

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

I'm trying to write an nunit unit test for a method that sends an email in C#. In the method being tested, a list of Attachments (System.Net.Mail.Attachment) is created and then items added to it.

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

In my Unit Test, I don't know how to mock emailAttachments.Add(new Attachment(file)). Or if it is even possible. Currently the unit test fails when it reaches this line as the 'file' doesn't exist. Do I create a test file and save it within the project and use/reference it? Or is there a better way to approach it?

TIA

I am assuming you are using System.Net.Mail for the messages with smtp client. If so, it would go something like this

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();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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