Mocking is a technique to replace actual objects with fake objects.Some other terms for fake objects are stubs and mocks.Mocking is useful for many reasons.There are several mocking frameworks available today such as Moq,NSubstitute,Rhino Mocks .
Rhino Mocks is a framework used in .NET for writing mock objects.Mock objects are objects which replace actual objects.Following are the uses of creating mock objects
- They allow to replace actual objects with mock objects
- You can tell the mock objects how to behave at runtime
- This helps in unit testing the code since you replace the external dependencies with mock objects
You create a mock object by using the code as below:
var stubEmployee = MockRepository.GenerateStub<IEmployee>(); var employee = new Employee{Name = "Amit"}; stubEmployee.Stub(x => x.GetEmployeeById(1)).Return(theUser);
In Rhino we create fake object by calling the GenerateStub() method.The type argument to this method is Interface which represents a dependency we want to mock.
Using Return method to return a specific value from a mock object method call
stubEmployee.Stub(x => x.GetEmployeeById(1)).Return(employee);
Asserting if a method is called on the mock object
mockEmployeeRepository.AssertWasCalled(x => x.GetId(Arg<string>.Is.Anything)));
Setting expectations
You can verify if the mock object satisfies some conditions such as property having specific value by using Expect() method.
IEmployee employee= MockRepository.GenerateMock<IEmployee>(); employee.Expect(employee=>employee.Name="john"); employee.Expect(employee=>employee.age=32);
Leave a Reply