I am new to using Mocks. But what are it’s main purposes? I’m going to start by using Moq to test my application (and NUnit).
For example, I have code that does things like this:
My webpage code behind:
public partial class MyWebpage
{
protected string GetTitle(string myVar)
{
return dataLayer.GetTitle(myVar);
}
}
My data access layer:
public class DataLayer
{
public string GetTitle(string myVar)
{
// Create the query we want
string query = "SELECT title FROM MyTable " +
"WHERE var = @myVar";
//ENTER PARAMETERS IN HERE
// Now return the result to the view
return this.dataProvider.ExecuteMySelectQuery(
dr =>
{
//DELEGATE DATA READER PASSED IN AND TITLE GETS RETURNED
},
query,
parameters);
}
}
My data provider talks and interacts directly with the db:
public class DataProvider
{
public T ExecuteMySelectQuery<T>(Func<IDataReader, T> getMyResult, string selectQuery, Dictionary parameters)
{
//RUNS AND RETURNS THE QUERY
}
}
What’s the best way to test all of this?
If you want to test the layers separately, you would need to create interfaces for your DataProvider and DataLayer classes that expose the methods that you want to Mock. Then you can use a mocking framework – NSubstitute is very good, less code to write to create the mocks – to mock out the calls to the dependent classes, leaving you to test the code within that specific unit
Then, in your test code, you create mocks instead of real objects and pass those into the constructor when you instantiate your test objects. To test the DataLayer: