Xpode.com        Click here to Print this article.

.NET testing interview questions: - What is Mock testing and how to implement it?

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: - 



http://
http://questpond.com/

Contributed by:
Shivprasad koirala Koirala
I am a Microsoft MVP for ASP/ASP.NET and currently a CEO of a small E-learning company in India. We are very much active in making training videos , writing books and corporate trainings. Do visit my site http://www.questpond.com for .NET, C# , design pattern , WCF , Silverlight , LINQ , ASP.NET , ADO.NET , Sharepoint , UML , SQL Server training and Interview questions and answers

Resourse address on xpode.com
http://www.xpode.com/Print.aspx?Articleid=715

Click here to go on website