简体   繁体   English

Java:如何在 static 子 class 中模拟受保护的方法

[英]Java: How to Mock a protected method inside a static child class

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.我在 static 子 class 中有一个受保护的方法。我正在运行一个测试用例,它成功但代码覆盖率没有增加。

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?有人可以在这里帮忙吗,我在做什么错误?

When you mock the constructor, then all internal method calls are also mocked and do not go through the actual code.当您模拟构造函数时,所有内部方法调用也会被模拟,并且不会通过实际代码进行 go 。

If you remove the following try-with-resources:如果删除以下 try-with-resources:

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

The real code will be executed and the coverage will increase.真正的代码会被执行,覆盖率会增加。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM