Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between stub and when in mockito

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?

like image 880
Ramya Avatar asked Feb 06 '13 18:02

Ramya


People also ask

What is stub in Mockito?

A stub is a fake class that comes with preprogrammed return values. It's injected into the class under test to give you absolute control over what's being tested as input. A typical stub is a database connection that allows you to mimic any scenario without having a real database.

What is the difference between a mock and a stub?

Stub: a dummy piece of code that lets the test run, but you don't care what happens to it. Substitutes for real working code. Mock: a dummy piece of code that you verify is called correctly as part of the test. Substitutes for real working code.

What are stubs and mocks in unit testing?

Stub - an object that provides predefined answers to method calls. Mock - an object on which you set expectations. Fake - an object with limited capabilities (for the purposes of testing), e.g. a fake web service. Test Double is the general term for stubs, mocks and fakes.

What is stub in unit testing?

A stub is a small piece of code that takes the place of another component during testing. The benefit of using a stub is that it returns consistent results, making the test easier to write. And you can run tests even if the other components are not working yet.


1 Answers

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.

like image 122
Brice Avatar answered Sep 24 '22 01:09

Brice