Let us say you want to UNIT test a data access layer class. But before any call is made to the data access class it calls an email class. This email component is not functional because we have still not received email server configuration details.
So now how do we UNIT test data access layer because the email class will never allow us to execute the data access layer code. This is achieved by mocking (by passing) the email code.
public class Email
{
public bool SendEmail()
{
// not configured throws error
}
}
public class ClsCustomerDAL
{
public bool SaveRecord(string
strCustomerName)
{
Email obj = new Email();
obj.SendEmail(); // This line
throws a error
// Data acess code goes at
this place but this place is never reached because // the error is throw in the
previous line
return true;
}
}
Implementing of Mock Test: -
You can implement mocking by using open source mocking frameworks like Rhino mocks, MOQ etc.
For example if we want to Mock the email class method by using MOQ tool we need to write the below code. Create the email object using the Mock class of MOQ framework.
Mock<Email> target = new
Mock<Email>();
Then write the code which you want to execute rather than executing the actual code. For instance now I want to just “return true” in a hard code manner.
target.Setup(x =>
x.SendEmail()).Returns(true);
Now any calls to the “target” email object will always return true.
Also see following .NET
testing interview questions video on implementing TDD (Test Driven
Development) in C# (Csharp) using VSTS Unit Testing: -