简体   繁体   中英

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.

I am using mockito-core version 2.7.22 , but I have also tried version 3.3.0 and the problem persists.

Here is some psuedocode example. I am testing a method in 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:

Type Mismatch. Cannot convert from Class >ClassA< to ClassA.

.mock works fine.

Recommends 1 fix: Add cast to 'ClassA'.

This happens to all classes that I try to spy, not just 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.

My mockito imports are:

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

EDIT: Adding the class hierarchy...

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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