Skip to content
Advertisement

How to mock a method call in a constructor?

I have class class1, which has 2 member variables:

classA
{
    private Boolean isEnable;
    private Config config;
   
    public classA(final Config config)
    {
        this.config = config;
        isEnable = config.getEnablingStatus();
    }

    public classB fun()
    {
        // Do something!
        // Return an object of classB!
    }
}

I want to test the method fun, so I will have to write a test-class and a test method for that. But, how do I mock the method call config.getEnablingStatus(), while creating an object of type classA in the test class?

I am thinking of doing something like this [see the below piece of code].Is it correct? But what is the right way to do it?

TestClassForClassA:

TestClassForClassA
{
    private Boolean isEnable;
    
    @Mock
    private Config config;
   
    @InjectMocks
    classA objA = new classA(config);

    @Before
    public void init() 
    {
        initMocks(this);
    }

    public void test1Fun()
    {
        // Does doing this, put the value of isEnable as true in the objA for this test?
        isEnable = true; 
        
        // Here write the code to test the method fun().
    }

    public void test2Fun()
    {
        // Does doing this, put the value of isEnable as false in the objA for this test?
        isEnable = false; 
        
        // Here write the code to test the method fun().
    }
}

Advertisement

Answer

Do not use @InjectMocks

Try something like this

public class TestClassForClassA {

    @Mock
    private Config config;

    private ClassA objA;

    @Before
    public void init() {
        MockitoAnnotations.initMocks(this);
    }

    @Test
    public void test1Fun() {
        Mockito.when(config.getEnablingStatus()).thenReturn(true);
        objA = new ClassA(config);
        ClassB objB = objA.fun();
        assertTrue(objB.isEnabled());
    }

    @Test
    public void test2Fun() {
        Mockito.when(config.getEnablingStatus()).thenReturn(false);
        objA = new ClassA(config);
        ClassB objB = objA.fun();
        assertFalse(objB.isEnabled());
    }

}

User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement