Unit tests doubles

Dummy objects are passed around but never actually used. Usually they are just used to fill parameter lists.

Stubs

Просто методите на stubs са хардкоднати да връщат винаги даден предефиниран резултат при различни сценарии. Дори не хвърлят и exceptions или каквото и да е от самата бизнес логика.

A stub provides predetermined responses to calls made during a test. For example, if testing a payment gateway, a stub can simulate both successful and failed transactions, ensuring your code responds appropriately.

Example: Your test class depends on a method Calculate() taking 5 minutes to complete. Rather than wait for 5 minutes you can replace its real implementation with stub that returns hard-coded values; taking only a small fraction of the time.

Or the network connection to twitter API is very slow, which make my test slow. I know it will return timelines, so I made a stub simulating HTTP twitter API, so that my test will run it very fast, and I can running the test even I’m offline.

Mocks

Very similar to Stub but interaction-based rather than state-based. This means you don’t expect from Mock to return some value, but to assume that specific order of method calls are made.
Example: You’re testing a user registration class. After calling Save, it should call SendConfirmationEmail.

Stubs and Mocks are actually sub types of Mock, both swap real implementation with test implementation, but for different, specific reasons.

Stubs don’t fail your tests, mock can.

Stub – for replacing a method with code that returns a specified result.

Mock – a stub with an assertion that the method gets called.

С mock например можеш да провериш дали при дадени сценарии тестваният метод ще хвърли или не exception, дали минава или фейлва например някаква валидация…
Със stub – не, там просто се връща нещо хардкоднато.

Example in JavaScript:

var Stub = {
method_a: function(param_a, param_b){
return 'This is an static result';
}
}

var Mock = {
calls: {
method_a: 0
}

method_a: function(param_a, param_b){
this.method_a++;
console.log('Mock.method_a its been called!');
}
}

Литература:

https://www.bairesdev.com/blog/stub-vs-mock

https://stackoverflow.com/questions/3459287/whats-the-difference-between-a-mock-stub

https://martinfowler.com/articles/mocksArentStubs.html