Reena Upadhyay
Reena Upadhyay

Reputation: 2017

Is it possible to mock all fields of second level mocked object using mockito

I am using mockito framework in junit test class.

Here is the dependency graph of classes:

First is dependent on Second, Second is dependent on Third and Fourth.

I want to test First class. In my test class, I have mocked instance of Second. Now I want, for a mocked instance of Second class, all fields of Second class should also get mocked i.e. mocked instance of Second class should have mocked instance of Third and Fourth class (Second class has two fields Third and Fourth).

In the below test class, I want mocked instance of Second should have mocked instance of Third and Fourth in it.

public class FirstTest {

   @Mock
    private Second second;

    @Mock
    private Third third;

    @Mock
    private Fourth fourth;

    @InjectMocks
    private First first = new First();

    @BeforeClass
    public void setUp() throws Exception {
        initMocks(this);
    }


    @Test
    public void testCallSecond() throws Exception {
        first.callSecond();
    }

}



public class First {

    @Autowired
    private Second second;

    public void callSecond() {
        second.call();
    }
}



public class Second {

    @Autowired 
    Third third;


    @Autowired 
    Fourth fourth;


    public void call() {

        System.out.println("third instance ======="+third);
        third.call();
    }


}

is it possible to mock all fields of second level mocked object? If yes then please suggest. I want to do it using Mockito framework only.

Upvotes: 0

Views: 2117

Answers (2)

DaveH
DaveH

Reputation: 7335

You are testing First and its interactions with Second by mocking Second. This means you are using a dummy version of Second that you can make return whatever you want when its methods are called.

First is unaware of the existence of Third and Fourth so there is no need to mock them at all.

Upvotes: 4

Timothy Truckle
Timothy Truckle

Reputation: 15634

You use the mocking framework to remove transient dependencies.

This means when testing First you mock Second and by doing so cut off all further dependencies.

in your test you verify that your code under test (cut) Firlst called the expected method on its dependency apllying the expected parameters and/or the output of your cut depending of the return value configured for the mock of Second

Upvotes: 3

Related Questions