Rajath
Rajath

Reputation: 11946

Mockito non-stubbed functions

I have just started using Mockito, so not very conversant with it. I have mocked an object like this:

CInjectorFactory mockFactory = mock(CInjectorFactory.class);

Now, if I don't stub a particular function, it doesn't call the original CInjectorFactory's function, and I get a 'null' value:

public CMainActivityHelper getMainActivityHelper()

Does this mean, that only stubbed functions are available for the mocked object? That this mocked object does not inherit the original functions from the object that is being mocked?

Thanks.

Upvotes: 1

Views: 3766

Answers (3)

obourgain
obourgain

Reputation: 9356

You can use :

CInjectorFactory mockFactory = mock(CInjectorFactory.class, Mockito.CALLS_REAL_METHODS);

Then, unstubbed methods will delegate to the real implementation.

Example from the Mockito.CALLS_REAL_METHODS javadoc :

Foo mock = mock(Foo.class, CALLS_REAL_METHODS);

 // this calls the real implementation of Foo.getSomething()
 value = mock.getSomething();

 when(mock.getSomething()).thenReturn(fakeValue);

 // now fakeValue is returned
 value = mock.getSomething();

Upvotes: 5

mikeslattery
mikeslattery

Reputation: 4119

The front page of the mockito website clearly shows how to stub method calls:

CMainActivityHelper expected = ...;
when(mockFactory.getMainActivityHelper()).thenReturn( expected );

Then when you call mockFactory.getMainActivityHelper() it will return expected.

Upvotes: 2

JB Nizet
JB Nizet

Reputation: 691973

Yes, that's the documented behavior:

By default, for all methods that return value, mock returns null, an empty collection or appropriate primitive/primitive wrapper value (e.g: 0, false, ... for int/Integer, boolean/Boolean, ...).

If you want the real methods to be called when not stubbed, you should spy the real object:

You can create spies of real objects. When you use the spy then the real methods are called (unless a method was stubbed).

Upvotes: 3

Related Questions