Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/342.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java Mockito doReturn().when()调用原始方法_Java_Unit Testing_Testing_Junit_Mockito - Fatal编程技术网

Java Mockito doReturn().when()调用原始方法

Java Mockito doReturn().when()调用原始方法,java,unit-testing,testing,junit,mockito,Java,Unit Testing,Testing,Junit,Mockito,我无法让Mockito重写我正在测试的类中的方法 @Test public void test_classToTest() throws Exception { DependencyA dependencyA = mock(DependencyA.class); DependencyB dependencyB = mock(DependencyB.class); DependencyC dependencyC = mock(DependencyC.class);

我无法让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);

我试图重写的方法是classToTest.storeContent(),它是从classToTest.copyContent()内部调用的。我知道这个类有点臭,但我不能重构它。但是,这不是一个非常复杂的设置,我不知道为什么要调用实际的.storeContent()方法

Mockito(和其他模拟工具)有一个限制,
final
方法不能被存根

可能您的
ClassToTest#storeContent
标记为
final


如果是这种情况,只需删除
final
关键字,存根机制就会启动。

Mockito(和其他模拟工具)中有一个限制,
final
方法不能存根

可能您的
ClassToTest#storeContent
标记为
final


如果是这种情况,只需删除
final
关键字,存根机制就会启动。

而不是使用
null
参数来设置我建议使用的模拟
storeContent
方法

例如


与其使用
null
参数来设置模拟的
storeContent
方法,我建议使用

例如


您正在测试的方法的方法签名是什么?传递给实际方法的参数值是什么?可能将
null
s替换为
any()
s?根据克里斯托弗的上述观点,请首先检查
storeContent
是否为
public
、非
static
和非
final
,并且ClassToTest同样为
public
和非
final
。(一般来说,我还建议不要在正在测试的类上使用
spy
,而是将类作为一个单元进行测试,而不是孤立地挑出方法;我理解这种吸引力,但对于大多数类来说,它假定了一些关于类实现的私有细节,而这些细节对测试并不重要。)您正在测试的方法的方法签名是什么?传递给实际方法的参数值是什么?可能将
null
s替换为
any()
s?根据克里斯托弗的上述观点,请首先检查
storeContent
是否为
public
、非
static
和非
final
,并且ClassToTest同样为
public
和非
final
。(一般来说,我还建议不要在您正在测试的类上使用
spy
,而是将类作为一个单元进行测试,而不是孤立地挑出方法;我理解这种吸引力,但对于大多数类,它假定了一些关于类实现的私有细节,而这些细节对测试并不重要。)就是这样。谢谢就这样。谢谢
import static org.mockito.ArgumentMatchers.*;

// ...

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