3

Possible Duplicate:
What is the purpose of mock objects?

I'm preparing a presentation and I need to get a better understanding of what mocking is, what is the purpose of using it, what are the common situations that I should use mock objects? I found out that there are a bunch of mocking frameworks out there. Do they all do the same thing or do I use a specific framework for specific testing purpose? What are the differences between these frameworks? Which one would you recommend for testing Java?

here are some stuff that I found:

1.MockingToolkitComparisonMatrix which seems biased.

2.What are mock objects in Java? This is a year old. I thought there might be some better answer today.

Thank you.

Community
  • 1
  • 1

3 Answers3

6

The purpose of mocking is to allow you to test your application components in isolation. For example, if you have a service that uses a DAO, you want to be able to test your service without actually having to go to the database via the DAO. You would

1) Test the DAO in isolation, and
2) Mock the DAO in your service tests, so your service can be tested in isolation.

Since your DAO has a clearly defined API, your mock DAO simulates that API. So if you have a findAll type method that your service calls, you can easily mock the DAO to expect a call to findAll and return the appropriate results.

The purpose of all mocking frameworks is the same -- to allow you to set up expectations and assert that those expectations were met in your tests. The details, however, are different between frameworks. I have used EasyMock in actual work environments, and played around with Mockito for answering a few questions on SO. Both are pretty nice. The cost of entry is fairly low -- the idea is always to set up expectations, get the mock to return the results, and then to verify that the expectations were met. You might have to take a day or 2 to understand your mocking framework, but after that you should be able to be productive and figure out what you don't know as you go.

hvgotcodes
  • 118,147
  • 33
  • 203
  • 236
5

In a good encapsulated design, a class should behave the same regardless of the implementation classes of its dependencies. Mocking allows you to isolate your implementation code such that you can inspect how it will react independent of more volatile constructs such as databases and file systems in a way that ensures a deterministic outcome.

nsfyn55
  • 14,875
  • 8
  • 50
  • 77
-1

A mock framework also should help to define that a certain method got called during a test.

So if your test does not call the specified method the mock framework will indicate that. Or you could specify that two methods are called in a specific order (open/close e.g.)

Angel O'Sphere
  • 2,642
  • 20
  • 18