MS Unit Testing with Mocking : Mock object which we unable to run and execute
Step : 1 Add 2 Class Library project "EmployeeLIB","NotificationLib" & UnitTestingproject
EmployeeLib:
namespace EmployeeLib
{
public class Employee
{
public bool AddEmployee(SendMail.MyEmail mail)
{
return mail.SendMail();
/// Add database operation code
}
}
}
NotificationLib :
namespace NotificationLib
{
public class MyEmails
{
public virtual bool SendMail()
{
MailMessage mail = new MailMessage();
SmtpClient SmtpServer = new SmtpClient("smtp.krishna.com");
mail.From = new MailAddress("your_email_address@krishna.com");
mail.To.Add("to_address");
mail.Subject = "Test Mail";
mail.Body = "This is for testing SMTP mail from krishna domain";
SmtpServer.Port = 587;
SmtpServer.Credentials = new System.Net.NetworkCredential("username", "password");
SmtpServer.EnableSsl = true;
SmtpServer.Send(mail);
return true;
}
}
}
Add unit test project and install Moq from nuget
namespace UnitTestEmployeeLib
{
[TestClass]
public class UnitTest1
{
[TestMethod]
public void TestAddEmployee()
{
// object
Mock<SendMail.MyEmails> obj = new Mock<SendMail.MyEmails>();
// function need to moq
obj.Setup(a => a.SendMail()).Returns(true);
EmployeeLib.Employee objEmp = new EmployeeLib.Employee();
bool result = objEmp.AddEmployee(obj.Object);
Assert.AreEqual(result, true);
}
}
}
No comments:
Post a Comment
Note: Only a member of this blog may post a comment.