简体   繁体   English

Mockito doReturn()。when()调用原始方法

[英]Mockito doReturn().when() calls original method

I can't get Mockito to override a method in the class I am testing. 我无法让Mockito覆盖正在测试的类中的方法。

@Test
public void test_classToTest() throws Exception {
    DependencyA dependencyA = mock(DependencyA.class);
    DependencyB dependencyB = mock(DependencyB.class);
    DependencyC dependencyC = mock(DependencyC.class);

    ClassToTest classToTest = ClassToTest.builder().dependencyA(dependencyA)
            .dependencyB(dependencyB).dependencyC(dependencyC).build();

    classToTest= Mockito.spy(classToTest);

    Mockito.doReturn("This is not the method you are looking for").when(classToTest).storeContent(null, null, null);

    String result = classToTest.copyContent(someVariable, SOME_CONSTANT);

The method I am trying to override is classToTest.storeContent() which is called from inside classToTest.copyContent(). 我试图覆盖的方法是classToTest.storeContent(),它是从classToTest.copyContent()内部调用的。 I am aware that this class is a little smelly, but I am not in a position to refactor it. 我知道这堂课有点臭,但我无法对其进行重构。 However, this is not a very complicated setup and I am not sure why the actual .storeContent() method is getting called. 但是,这不是一个非常复杂的设置,我不确定为什么要调用实际的.storeContent()方法。

Instead of using the null parameters to setup the mocked storeContent method I would suggest using ArgumentMatchers.any 建议不要使用null参数来设置storeContent方法,而建议使用ArgumentMatchers.any

Eg 例如

import static org.mockito.ArgumentMatchers.*;

// ...

Mockito.doReturn("This is not the method you are looking for").when(classToTest).storeContent(any(), any(), any());

There is a limitation in Mockito (and other mocking tools), that final methods cannot be stubbed. Mockito(和其他模拟工具)有一个限制,即不能对final方法进行存根。

Maybe your ClassToTest#storeContent is marked as final ? 也许您的ClassToTest#storeContent标记为final

If this is the case, just remove the final keyword, and the stubbing mechanism should kick-in. 如果是这种情况,只需删除final关键字,即可启动存根机制。

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

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