Scenario 1
TestContext tContext = (TestContext)TestContextUtility.GetData(Constants.TestContextKey);
TestContextUtility is a class which returns an object when GetData property is accessed (it also expects a string parameter). You want to mock this using moles.
Solution:
TestContext ctx = new TestContext();
MTestContextUtility.GetDataString = (s) => { return ctx; };
...where MTestContextUtility is generated by Moles, s is the expected string parameter variable (no need to declare this anywhere) and the method body returns TestContext object.
Scenario 2
ValResult res = CommonValidation.CreateValResult(settings, tContext.Info, true);
CreateValResult method returns a ValResult object. It accepts 3 parameters, the 3rd parameters being boolean. You want to return a mock ValResult and bypass the logic in CreateValResult
Solution:
MCommonValidation.CreateValResultSettingsInfoBoolean = (d, u, p) =>
{
return
new ValResult
{
ErrorMessage = "this is an error",
ErrorNumber = "123"
};
};
...where MCommonValidation is generated by Moles, d, u, p are variables and method returns a mock ValResult object. You can return this object based on input conditions too.
Scenario 3
When you need to mock a private method:
public class EmployeeProvider
{
public CreateEmployeeContext
{
dbemp = ..//get from database
//then parse
var parsedEmployee = ParseEmployee(dbemp);
}
}
EmployeeProvider class provides an employee through public method CreateEmployeeContext
//private method which parses db employee to employee entity
private Employee ParseEmployee(DBEmployee emp)
{
Employee e = new Employee();
e.Name = emp.Name;
}
ParseEmployee is the private method which we wish to mock
Solution:
MEmployeeProvider.AllInstances.ParseEmployeeDBEmployee = (a,b) => { return new Employee{ Name="test" };};
...where a is DBEmployee and b is Employee (return type)
No comments :
Post a Comment