Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Hard-Coded Mock Objects vs Mocking Framework

I'm curious as to what method people like to use for mocking and why. The two methods that I know of are using hard coded mock objects and a mocking framework. To demonstrate, I'll outline an example using C#.

Suppose we have an IEmployeeRepository interface with a method called GetEmployeeById.

public interface IEmployeeRepository
{
    Employee GetEmployeeById(long id);
}

We can easily create a mock of this:

public class MockEmployeeRepository : IEmployeeRepository
{
    public Employee GetEmployeeById(long id)
    {
        Employee employee = new Employee();
        employee.FirstName = "First";
        employee.LastName = "Last";
        ...
        return employee;
    }
}

Then, in our tests we can explicitly tell our services to use the MockEmployeeRepository, either using a setter or dependency injection. I'm new to mocking frameworks so I'm curious as to why we use them, if we can just do the above?

like image 685
Brian DiCasa Avatar asked Dec 06 '10 20:12

Brian DiCasa


People also ask

What are mocking frameworks?

What is a mocking framework? Mocking frameworks are used to generate replacement objects like Stubs and Mocks. Mocking frameworks complement unit testing frameworks by isolating dependencies but are not substitutes for unit testing frameworks.

What is the difference between mocking and stubbing?

Stubbing, like mocking, means creating a stand-in, but a stub only mocks the behavior, but not the entire object. This is used when your implementation only interacts with a certain behavior of the object.

What is the goal of using mock object or mocking?

Using mock objects allows developers to focus their tests on the behavior of the system under test without worrying about its dependencies. For example, testing a complex algorithm based on multiple objects being in particular states can be clearly expressed using mock objects in place of real objects.

Which framework is used to create mocked objects?

Creating mock objects manually is very difficult and time-consuming. So, to increase your productivity, you can go for the automatic generation of mock objects by using a Mocking Framework. A developer can build his/her unit test by using any of the NUnit, MbUnit, MSTest, xUnit etc.


1 Answers

A mocked interface can have different outputs per test - One test you may have a method return null, another test has the method return an object, another test has the method throw an exception. This is all configured in the unit test, whereas your version would require several hand-written objects.

Psuedocode:

//Unit Test One

MockObject.Expect(m => m.GetData()).Return(null);

//Unit Test Two

MockObject.Expect(m => m.GetData()).Return(new MyClass());

//Unit Test Three

MockObject.Expect(m => m.GetData()).ThrowException();
like image 199
Meff Avatar answered Nov 06 '22 01:11

Meff