44

I am new to mockito.

need to know difference between stub and when

      1. stub(cpproxy.getBinList()).toReturn(gettestbins());
      2. when(cpproxy.getBinList()).thenReturn(gettestbins());

whats the difference between these two?

bric3
  • 40,072
  • 9
  • 91
  • 111
Ramya
  • 1,067
  • 6
  • 16
  • 29

1 Answers1

79

Actually they are technically the same. When Mockito was first created, we were talking about stubs, so the vocabulary followed that idea. Later people thought it was better to think in interactions rather that technical terms, so the vocabulary followed the when ... then ... style. This change in vocabulary helps people to think about interactions, messaging between object. Which is the most interesting idea (message passing) thing in an object oriented language (quoting Alan Kay).

Nowadays testing approach has evolved to Behavior Driven Development (from Dan North), which is almost the same thing but focus even more on the behavior at design time. To reflect that thinking, people asked Mockito to offer an API that reflect that change. So you also use given ... will ... style from BDDMockito

given(the_type.performs_that()).willReturn(something)

This is my preferred vocabulary now as I use tests to drive my objects design.

Community
  • 1
  • 1
bric3
  • 40,072
  • 9
  • 91
  • 111
  • 1
    When you say "technically the same", what do you mean? Do you mean that they do all the same things, but it's just different names? (That's my understanding, but I'd like it cleared up a little) – Nic Sep 12 '18 at 22:26
  • 1
    @NicHartley Yes `BDDMockito` `given` / `when` style are just aliases, and they rely on the same technical code. In Mockito 2.x `BDDMockito` offers additional methods to enable the developer to use behaviour driven development in more place, especially for the verification, while the API is not that symmetric in this case, the internals remains the same. – bric3 Sep 13 '18 at 09:19