Andrew
Andrew

Reputation: 621

How do I mock call method from testable class?

Want to ask you a question.

How should I properly return some data from method called from testable class ?

For example I have next structure:

Class SomeClass {
    public void method1(){
    //some logic here
    List<Object> howToReturnHereValues = gatData();
    //some logic here
    }
    public List<Object> getData(){

       return List<Object>;

    }
}

Right now I want to test method1(), but I don't know how to mock call getData() which returns List<Object>.

Any advice please ?

Upvotes: 3

Views: 1194

Answers (2)

StefK
StefK

Reputation: 674

You can do this using a spy, like explained here: https://static.javadoc.io/org.mockito/mockito-core/2.7.17/org/mockito/Mockito.html#13

Example:

@Test
public void testMethod1() throws Exception {
    SomeClass someClass = new SomeClass();
    SomeClass spy = Mockito.spy(someClass);
    Mockito.when(spy.getData()).thenReturn(Arrays.asList("blaat", "blabla"));
    spy.method1();
}

This will return a List of "blaat" and "blabla" which can be used by the logic in your method1.

Upvotes: 3

davidxxx
davidxxx

Reputation: 131326

Right now I want to test method1(), but I don't know how to mock call getData() which returns List.

It is rather a bad idea to mock a public method of a class that is under test.

A unit test should test a behavior and mock dependencies. Here, you unit test only a part of the behavior as you mock the behavior of the tested class.

If the class is ours you could :

  • either test this method without mocking the getData() called public method.
  • or move the getData() public method in another class and then mock this new dependency if you don't want to repeat the test of the getData() method in each test method calling it.

If the class is not modifiable and the mocked called is really required, you could use the spy() method of the Mockito framework on the object under test to simulate a mocked behavior for a specific method.

Upvotes: 2

Related Questions