[java] Mocking member variables of a class using Mockito

I am a newbie to development and to unit tests in particular . I guess my requirement is pretty simple, but I am keen to know others thoughts on this.

Suppose I have two classes like so -

public class First {

    Second second ;

    public First(){
        second = new Second();

    public String doSecond(){
        return second.doSecond();

class Second {

    public String doSecond(){
        return "Do Something";

Let's say I am writing unit test to test First.doSecond() method. However, suppose, i want to Mock Second.doSecond() class like so. I am using Mockito to do this.

public void testFirst(){
    Second sec = mock(Second.class);
    when(sec.doSecond()).thenReturn("Stubbed Second");

    First first = new First();
    assertEquals("Stubbed Second", first.doSecond());

I am seeing that the mocking does not take effect and the assertion fails. Is there no way to mock the member variables of a class that I want to test . ?

This question is related to java mocking mockito

The answer is

You need to provide a way of accessing the member variables so you can pass in a mock (the most common ways would be a setter method or a constructor which takes a parameter).

If your code doesn't provide a way of doing this, it's incorrectly factored for TDD (Test Driven Development).

Similar questions with java tag:

Similar questions with mocking tag:

Similar questions with mockito tag: