如何使用 Mockito 来模拟受保护的方法?

问题描述 投票:0回答:8

我使用的是 Mockito 1.9.5。我如何模拟受保护方法返回的内容?我有这个受保护的方法...

protected JSONObject myMethod(final String param1, final String param2)
{
…
}

但是,当我尝试在 JUnit 中执行此操作时:

    final MyService mymock = Mockito.mock(MyService.class, Mockito.CALLS_REAL_METHODS);        
    final String pararm1 = “param1”;
    Mockito.doReturn(myData).when(mymock).myMethod(param1, param2);

在最后一行,我收到编译错误“方法‘myMethod’不可见。”如何使用 Mockito 来模拟受保护的方法?如果这是答案,我愿意升级我的版本。

junit mocking mockito protected
8个回答
58
投票

这不是 Mockito 的问题,而是普通的旧 java 的问题。从您调用该方法的位置,您没有可见性。这就是为什么它是编译时问题而不是运行时问题。

几个选项:

  • 在与模拟类相同的包中声明您的测试
  • 如果可以的话,改变方法的可见性
  • 创建一个扩展模拟类的本地(内部)类,然后模拟这个本地类。由于该类是本地类,因此您可以看到该方法。

25
投票

回应 John B 的回答中对选项 3 的代码示例的请求:


public class MyClass {
    protected String protectedMethod() {
        return "Can't touch this";
    }
    public String publicMethod() {
        return protectedMethod();
    }
}

@RunWith(MockitoJUnitRunner.class)
public class MyClassTest {

    class MyClassMock extends MyClass {
        @Override
        public String protectedMethod() {
            return "You can see me now!";
        }
    }

    @Mock
    MyClassMock myClass = mock(MyClassMock.class);

    @Test
    public void myClassPublicMethodTest() {
        when(myClass.publicMethod()).thenCallRealMethod();
        when(myClass.protectedMethod()).thenReturn("jk!");
    }
}

15
投票

您可以使用Spring的ReflectionTestUtils按原样使用您的类,而无需仅为了测试而更改它或将其包装在另一个类中。

public class MyService {
    protected JSONObject myProtectedMethod(final String param1, final String param2) {
        return new JSONObject();
    }

    public JSONObject myPublicMethod(final String param1) {
        return new JSONObject();
    }
}

然后在测试中

@RunWith(MockitoJUnitRunner.class)
public class MyServiceTest {
    @Mock
    private MyService myService;

    @Before
    public void setUp() {
        MockitoAnnotations.initMocks(this);
        when(myService.myPublicMethod(anyString())).thenReturn(mock(JSONObject.class));
        when(ReflectionTestUtils.invokeMethod(myService, "myProtectedMethod", anyString(), anyString())).thenReturn(mock(JSONObject.class));
    }
}

4
投票

使用 doReturn() 和 Junit5 的 ReflectionSupport,类似以下内容对我有用。

[注:我在 Mockito 3.12.4 上测试]

ReflectionSupport.invokeMethod(
        mymock.getClass()
//              .getSuperclass()     // Uncomment this, if the protected method defined in the parent class.
                .getDeclaredMethod("myMethod", String.class, String.class),
        doReturn(myData).when(mymock),
        param1,
        param2);

1
投票

John B 是对的,这是因为你要测试的方法是受保护的,这不是 Mockito 的问题。

除了他列出的选项之外,另一个选项是使用反射来访问该方法。这将使您避免更改正在测试的方法,并避免更改用于编写测试的模式以及存储这些测试的位置。我必须自己做一些测试,在这些测试中我不允许更改现有的代码库,其中包括大量需要进行单元测试的私有方法。

这些链接解释了 Reflection 以及如何很好地使用它,所以我将链接到它们而不是复制:


0
投票

WhiteBox.invokeMethod() 可以很方便。


0
投票
MyService myService = new MyService() {
    MyService callProtectedMethod(String param1, String param2) {
        myMethod(param1, param2);
        return this;
    }
}.callProtectedMethod(param1, param2);

// your assertion here: trivial e.g. assertNotNull(myService);

-1
投票
public class Test extend TargetClass{
    @Override
    protected Object method(...) {
        return [ValueYouWant];
    }  
}

在 Spring 中,您可以将其设置为高优先级,如下所示:

@TestConfiguration
public class Config {

    @Profile({"..."})
    @Bean("...")
    @Primary  // <------ high-priority
    public TargetClass TargetClass(){
        return new TargetClass() {
            @Override
            protected WPayResponse validate(...)  {
                return null;
            }
        };
    }
}

覆盖origin bean也是一样的

© www.soinside.com 2019 - 2024. All rights reserved.