When sending email using smtpclient, we can create ismtpclient interfaces and Smtpclientwrapper adaptation classes, mock or custom fackesmtpclient ismtpclient in unit tests, But Ndumbster's Facke SMTP Server provides us with a more intuitive and straightforward way to unit test. You can search for ndumbster through NuGet , which uses netdumbster.
1.IEmailSender interface
Public Interface iemailsender{ void SendMail (stringfromstringstring string body);}
2.SMTPAdapter Implementation Class
Public Interface Public classsmtpadapter:iemailsender{ Public voidSendMail (string from,stringTo,stringSubjectstringbody) { varMessage =NewMailMessage (); Message. Isbodyhtml=true; Message. from=NewMailAddress ( from); Message. To.add (Newmailaddress (to)); Message. Subject=subject; Message. Body=body; using(varSmtpClient =NewSmtpClient ()) { if(Smtpclient.host = =NULL) {Smtpclient.host="localhost"; } smtpclient.send (message); } }}
3. Using the Ndumbster Unit test
Public classsmtpadaptertest{[Fact] Public voidsendmailtest () {simplesmtpserver server= Simplesmtpserver.start ( -); Iemailsender Sender=NewSmtpadapter (); Sender. SendMail ("[email protected]","[email protected]","subject","Body"); Assert.equal (1, server. Receivedemailcount); Smtpmessage Mail= (smtpmessage) server. receivedemail[0]; Assert.equal ("[email protected]", Mail. headers[" from"]); Assert.equal ("[email protected]", Mail. headers[" to"]); Assert.equal ("subject", Mail. headers["Subject"]); Assert.equal ("Body", Mail. messageparts[0]. Bodydata); Server. Stop (); }}
asp: SmtpClient of Unit Testing