简体   繁体   English

我的 mockito 间谍方法不起作用。 类型不匹配错误

[英]My mockito spy method is not working. Type mismatch Error

Using mockito for the first time and spy doesn't seem to be working, and gives an error when I try to use it.第一次使用mockito并且 spy 似乎没有工作,当我尝试使用它时会出错。

I am using mockito-core version 2.7.22 , but I have also tried version 3.3.0 and the problem persists.我正在使用mockito-core version 2.7.22 ,但我也尝试过version 3.3.0并且问题仍然存在。

Here is some psuedocode example.这是一些伪代码示例。 I am testing a method in ClassA:我在 ClassA 中测试一个方法:

public class ClassATest{

    private ClassA classAMock;

    private ClassB classBMock;

    private ClassC classCMock;


    @Before
    public void setUp() {
        ClassBMock = Mockito.mock(ClassB.class);
        ClassCMock = Mockito.mock(ClassC.class);

        ClassAMock = Mockito.spy(ClassA.class);

    }


The.spy line gives an error that says: .spy 行给出了一个错误,上面写着:

Type Mismatch.类型不匹配。 Cannot convert from Class >ClassA< to ClassA.无法从 Class >ClassA< 转换为 ClassA。

.mock works fine. .mock工作正常。

Recommends 1 fix: Add cast to 'ClassA'.推荐 1 个修复:将演员表添加到“ClassA”。

This happens to all classes that I try to spy, not just ClassA .这发生在我试图监视的所有类中,而不仅仅是ClassA

I also know that if I use the @Spy Annotation instead, I get no errors, but the mocking outright fails to mock, like my 'when' methods run the real methods instead of the mocked ones.我也知道,如果我改用@Spy Annotation ,我不会收到任何错误,但是 mocking 完全无法模拟,就像我的“何时”方法运行真实方法而不是模拟方法一样。

My mockito imports are:我的 mockito 进口是:

import org.mockito.Mockito;
import static org.mockito.Matchers.any;
import static org.mockito.Mockito.when;

EDIT: Adding the class hierarchy...编辑:添加 class 层次结构......

public class ClassA{}
public class ClassB{}
public class ClassC{}

If anyone could help me out it would be greatly appreciated!如果有人可以帮助我,将不胜感激!

Thanks.谢谢。

This example works for me:这个例子对我有用:

public class ClassATest {

    private ClassA classAMock;
    private ClassB classBMock;
    private ClassC classCMock;

    @Before
    public void setUp() {
        classAMock = Mockito.spy(ClassA.class);
        classBMock = Mockito.mock(ClassB.class);
        classCMock = Mockito.mock(ClassC.class);
    }

    @Test
    public void test() {
        System.out.println(classAMock.getClass());
    }

    public static class ClassA {}
    public static class ClassB {}
    public static class ClassC {}
}

If it also does on your side, maybe you have a starting point and you could advance it until the problem occurs.如果它也在你身边,也许你有一个起点,你可以推进它直到问题发生。

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

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