user5417542
user5417542

Reputation: 3376

Mockito - mocking only a method

So I have following problem:

I have a class and I created three objects of it (obj1, obj2, obj3). I assigned them various values via setter-methods in my Testclass, since they will be used in a list later on.

The thing is, the class has a method, which returns a boolean, and it gets the value via SAP-Services, which of course I don't want to mock. So of course I want to use the when-method from Mockito to make sure, they return different values, because the class I want to test, sorts the files based on what they return on the method.

when(obj1.method()).thenReturn(true);
when(obj2.method()).thenReturn(false);
when(obj3.method()).thenReturn(true);

To do this, I need to mock the objects:

@mock
private Object obj1;

and in my setUp:

obj1 = mock(Object.class);

But when I do this, it won't allow me to set values for the objects.

How do I do that nonetheless, I need to fill the objects with some things, I can't leave them blank. It's only that there's no other way to set the return-value of the method than to mock the object..

Upvotes: 0

Views: 234

Answers (2)

Nikolay Tsankov
Nikolay Tsankov

Reputation: 51

If you want to mock only some methods of the object, you can use @Spy The method should be mocked a bit differently in this case though doReturn(true).when(obj1).method();

See http://docs.mockito.googlecode.com/hg/1.9.5/org/mockito/Spy.html for more info

Upvotes: 1

lance-java
lance-java

Reputation: 27958

Never use @Mock obj1 and obj1 = mock(Object.class); together... they are both doing the same thing and one is overriding the other.

If you use @RunWith(MockitoJunitRunner.class) and @Mock you don't need mock(...) (most of the time).

Also, I doubt that obj1 should be of type Object, I'm guessing it should be a more specific interface type.

Upvotes: 1

Related Questions