Jump to content

Mocking vs Stubbing

BrownZeus

Can someone explain to me the diffrence between mocking and stubbing an api/api response?

 

From what I can tell they accomplish the same thing, but mocking just takes extra steps

Link to comment
Share on other sites

Link to post
Share on other sites

A stub is a short piece of code that doesn't do anything, but to comply with all requirements of framework or language. So stubbing is there just to place some kind of "placeholders" if you will. Mocking is, on the other hand, some outlining how the method/API call should behave on some input, but again, it is not functioning properly (not real processing is happening within the API call). Mocking is there to test API design from 10000 ft overview, whether the API call gives you all the necessary information to properly progress in the action and so on.   

Link to comment
Share on other sites

Link to post
Share on other sites

A stub is something you want to be called, but only provides a canned response if has to provide a response. e.g., if you have a method "getTemperature", the method simply returns a number rather than actually get data from somewhere.

 

A mock is something that simulates some part of your system when that part of the system for whatever reason does not exist or is impractical to use for your test. A simple example would be if we had the "getTemperature" method, instead of returning a fixed number, it returns a random number. But for something more complicated like testing a database management app, you may substitute in a database with some test data (the "mock") rather than the actual database you're going to be working with, since the actual database may be huge.

 

As a personal example since I had to do this recently, I'm implementing code to talk to a new piece of hardware. But we don't have the hardware yet, only the communication documentation. So as a "mock", I made something that simulates how this hardware responds according to the communication documentation with random values. If I wanted to do the stub approach, the responses would be fixed.

 

EDIT: I guess the tl;dr is you use stubs to test your implementation, you use mocks in lieu of the real thing to test your design.

Link to comment
Share on other sites

Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

×