I have a Mocking.sln
which has two projects: Student
(Class Library) and StudentStat
(Console Application)
Student
project has below details:
private static Dictionary<int, int> GetStudentData()
{
// Key: Student ID Value: Total marks(marks in math + marks in physics)
Dictionary<int, int> studentResultDict = new Dictionary<int, int>();
using (SqlConnection con = new SqlConnection("Data Source=.;Initial Catalog=myDB;Integrated Security=true"))
{
con.Open();
string cmdStr = "Select * from Student";
using (SqlCommand cmd = new SqlCommand(cmdStr, con))
{
using (SqlDataReader reader = cmd.ExecuteReader())
{
while (reader.Read())
{
studentResultDict.Add((int)reader["ID"], (int)reader["MarksInMath"] + (int)reader["MarksInPhysics"]);
}
}
}
}
return studentResultDict;
}
public static void CalculateTotalMarks()
{
Dictionary<int, int> studentResultDict = GetStudentData();
foreach (var item in studentResultDict)
{
Console.WriteLine("{0}\t{1}", item.Key, item.Value);
}
}
StudentStat
project has below details:
class Program
{
static void Main(string[] args)
{
StudentInfo.CalculateTotalMarks();
}
}
This GetStudentData(
) method read details from DB and output details. Suppose this is my production code and I have no permission to change anything.
I have a overloaded version of GetStudentData()
which takes filePath as a parameter and read the details from text file. Below is the method:
private static Dictionary<int, int> GetStudentData(string filepath)
{
Dictionary<int, int> studentResultDict = new Dictionary<int, int>();
foreach (var item in File.ReadAllLines(filepath))
{
string[] data = item.Split(new string[] { "|" }, StringSplitOptions.RemoveEmptyEntries);
studentResultDict.Add(Convert.ToInt32(data[0]), Convert.ToInt32(data[1]) + Convert.ToInt32(data[2]));
}
return studentResultDict;
}
Now when I call StudentInfo.CalculateTotalMarks()
in StudentStat.exe
, I want this overloaded GetStudentData(string filepath)
will be called instead of the other method (which reads data from DB), and shows me output.
I heard that this will be possible using NMock3
. but I dont have any idea on that. Can you please share soem code samples..It will help me to learn NMock3
also. Any help is appreciated...