【问题标题】:Not able to mock the protected variable of object using mockito?无法使用 mockito 模拟对象的受保护变量?
【发布时间】:2025-12-27 04:15:06
【问题描述】:

我试图模拟对象但失败了。

Class A {
protected SomeResponse someRespsoonse;


public SomeResponse mapping(){

someResponse = new SomeResponse();

return someResponse ;
} 
}

然后我需要使用以下类对其进行测试:

@RunWith(MockitoJUnitRunner.class)
@PrepareForTest(A.class)
class ATest{
@Mock
A a = Mocktio.mock(A.class);
@Mock               
SomeResponse someResponse = Mockito.mock(SomeResponse.class);                              

@Test
testMyResponse{                
someResponse.setErrorInfo("500");                

PowerMockito.whenNew(SomeResponse.class).withNoArguments().thenReturn(someResponse);                
a.mapping();                

// some blah blah              

}}                          

问题无法从测试类填充 SomeResponse 对象。 我浏览了 * 和谷歌。但找不到想要的东西。

【问题讨论】:

    标签: unit-testing mockito


    【解决方案1】:

    您正在使用 PowerMockito 的 whenNew(),因此将您的 RunWith Runner 从 Mockito 更改为 PowerMock。

    @RunWith(PowerMockRunner.class)
    @PrepareForTest(A.class)
    class ATest{
    

    【讨论】:

    • 虽然测试用例正在运行,但现在无法进行测试覆盖。
    • 用 PowerMockRunner 或 MockitoJunitRunner 运行 junit 测试用例就像用普通的 junit 测试套件或运行器运行一样,它们与 cobertura 覆盖无关。检查您使用的 cobertura 插件和配置的方式和配置。
    • eclEmma 是 eclipse 自带的默认覆盖工具
    • 我通常使用 maven 插件运行 cobertura 报告。所以不知道 eclEmma 工具。最好在eclipse中的eclEmma覆盖工具上发布另一个问题,并告知您使用了powermockito框架,有人会为您提供解决方案。
    • 看起来你不会使用 powermock 获得 cobertura 覆盖。请参阅参考资料http://*.com/questions/23363212/powermock-eclemma-coverage-issue