I have a function which creates a report and sends it to a user. What I've done is create a mock for the email function, and verify if the 'send' function of the email class was called.
So now I know that the function is called, but how do you unit test the body of the Send() function? How can I prove that the subject and body are correct and an attachment is attached to the email?
Optionally you may add to the bottom of the email who the original recipient would have been. If you need to then confirm that the email was received you would have to write some code to actually check the email address and then confirm the message is correct. Not sure if this is what you mean or not.
The idea is to develop a unit test by following these 3 simple steps: Arrange – setup the testing objects and prepare the prerequisites for your test. Act – perform the actual work of the test. Assert – verify the result.
Can be done in following ways.
Step 1: Navigate to your Web.Config
file and add the following tags to it.
<system.net> <mailSettings> <smtp deliveryMethod="SpecifiedPickupDirectory"> <specifiedPickupDirectory pickupDirectoryLocation="E:\MailTest\"/> </smtp> </mailSettings> </system.net>
Make sure the directory you have specified for pickup location must exist.
Step 2 : Now test your email sending functionality. I have used button_click
to test this functionality with the following code.
SmtpClient smtp = new SmtpClient(); MailMessage message = new MailMessage("[email protected]", "[email protected]","My Message Subject","This is a test message"); smtp.Send(message);
Output : It will create .eml
files inside the folder with a randonly generated GUID name, which is the email that we can see after receiving it. For me it created a file like c127d1d5-255d-4a5a-873c-409e23002eef.eml
in E:\MailTest\
folder
Hope this helps :)
In your unit test tell your mocking framework to expect a call to Send()
with a specific body text.
Example for Rhino Mocks:
var mockMail = MockRepository.GenerateMock<Mail>(); mockMail.Expect( m => m.Send("ExpectedFrom", "ExpectedTo", "ExpectedSubject", "ExpectedBodytext") ); mockMail.Send(...whatever...); mockProvider.VerifyAllExpectations();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With