Home > Mobile >  Java: How to Mock a protected method inside a static child class
Java: How to Mock a protected method inside a static child class

Time:04-14

I am having a protected method inside a static child class. I am running a testcase , its getting successful but code coverage is not increasing.

public class A{
    private static final String var1 = "key1";
    protected static class B extends OsCmd{
        private String abc1;
        private String abc2;
        protected B(String xyz, String xyz2) {
            this.abc1 = xyz;
            this.abc2 = xyz2;
        }
        @Override
        protected void updateEnv(Map<String, String> env) {
            env.put(VAR1, "FALSE");
            env.put(VAR2, "TRUE");

            env.put("key3", abc1);
            env.put("key4", abc2);
    }
}
}

Below is my test case

@ExtendWith(MockitoExtension.class)
public class ATest {

    private A mockA;

    @BeforeEach
    public void setup() {
        mockA = Mockito.spy(A.class);
    }
    
    @Test
    public void test2() {
    try (MockedConstruction mockedConstruction =
                 mockConstruction(A.B.class)) {
        Map<String, String> map = new HashMap<String, String>();
        map.put("key1", "value1");
        A.B mockB =
                new A.B("a", "b");
        //doNothing().when(mockB).updateEnv(map);
        mockB.updateEnv(map);
    }
}

}

Can someone please help here, what mistake i am doing?

CodePudding user response:

When you mock the constructor, then all internal method calls are also mocked and do not go through the actual code.

If you remove the following try-with-resources:

try (MockedConstruction mockedConstruction =
                 mockConstruction(A.B.class))

The real code will be executed and the coverage will increase.

Best regards.

  • Related