0

May be I misunderstand the concept of mock object. I saw some post in stackoverflow for understanding when I should use mock object. Really I don't know when must I use mock object. I give an example of book Growing Object-Oriented Software, Guided by Tests:

context.checking(new Expectations() {{
    oneOf (turtle).turn(45);
}});

Usage is simple:

Is turn method executed only once? If is true test will be pass. If not test will be failed. This is my understanding of mock object.

Martin Fowler in Mocks Aren't Stubs said:

Mocks use behavior verification, where we instead check to see if the SUT made the correct calls on the collaborator.

But my question is why we need verify behavior of collaborator object (in this case turtle) if we want to unit test SUT?

Community
  • 1
  • 1
Seyed Morteza Mousavi
  • 6,855
  • 8
  • 43
  • 69
  • A unit test should isolate every variable except the one that you are testing. So if a method requires several things to get it to run, then you mock those items, giving you specific inputs. Then you can assure (assert) that you get the same output each time. – crthompson Aug 26 '14 at 16:40
  • @paqogomez I think it is job of stub. – Seyed Morteza Mousavi Aug 26 '14 at 16:57
  • 1
    [Mocks aren't stubs](http://martinfowler.com/articles/mocksArentStubs.html), you may enjoy [this excellent answer](http://stackoverflow.com/a/17810004/2589202) as well. – crthompson Aug 26 '14 at 17:02

1 Answers1

1

As suggested there is a very interesting article written by Martin Fowler http://goo.gl/85qY where you can really see by examples the concepts of a mock and a stub.

First thing clarify if you need a mock or a stub.

Mock is about behaviors or methods.

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 unit test, you should mock the collaborators of the class because they are not under test. For instance an object you use to persist against a data source because during your unit test you do not want to persist anything, test in isolation from the rest of the system.

Stubs

Stubs provide canned answers to calls made during the test, usually not responding at all to anything outside what's programmed in for the test. Stubs may also record information about calls, such as an email gateway stub that remembers the messages it 'sent', or maybe only how many messages it 'sent'.

Have a look at Mockito for instance http://goo.gl/zujvY in order to see what a mocking framework can do but before clarify if you want to test behavior or the status of an object.