简体   繁体   中英

What is the difference between stubs and mocks in the context of test spy? (jasmine)

I was reading this document sinonjs.org and to me is not clear the different between stubs and mocks.
Could someone explain me with simple words and some example the difference between stubs and mocks?

PS:
I already read about What is the difference between mocks and stubs ( JMock) , but the answers have no examples.

I will try to explain in a few words:

  • mock: use it if you are going to verify a collaboration in your SUT. You have to mock the collaborator and then verify if the collaboration is done.

     var collaborator = {}; collaborator.collaboration = sinon.mock(); SUT.setCollaborator(collaborator); SUT.play(); collaborator.collaboration.verify(); 
  • stub: use it if you need a collaborator fot your SUT, but the test is not testing the collaboration.

     var collaborator = {}; collaborator.collaboration = sinon.stub().returns(1); SUT.setCollaborator(collaborator); SUT.play(); 

The technology underneath stubs and mocks is similar, the difference is the intention of the test.

From http://sinonjs.org/docs/#mocks :

Mocks come with built-in expectations that may fail your test. Thus, they enforce implementation details. The rule of thumb is: if you wouldn't add an assertion for some call specific, don't mock it. Use a stub instead.

Below important notes will help you to understand the exact difference between Spies, Stubs and Mocks:

  • Spies , which offer information about function calls, without affecting their behavior
  • Stubs , which are like spies, but completely replace the function. This makes it possible to make a stubbed function do whatever you like — throw an exception, return a specific value, etc
  • Mocks , which make replacing whole objects easier by combining both spies and stubs

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM