Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
648 views
in Technique[技术] by (71.8m points)

unit testing - 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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

That's not a Mock, it's a Stub. For stubbing, your example is perfectly acceptable.

From Martin Fowler:

Mocks are what we are talking about here: objects pre-programmed with expectations which form a specification of the calls they are expected to receive.

When you're mocking something, you usually call a "Verify" method.

Look at this for the diff between Mocks and Stubs http://martinfowler.com/articles/mocksArentStubs.html


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...