0
votes

Today while working with Mockito and spring I got struck with this scenario,

    public class MyClass {

    private MyService myService;

    int doSomethingElse(String str) {
        .....
        myService.doSomething(str);
        ...
    }
}

public interface MyService {
    String doSomething(String str);
}


public class Class1 {
    private MyClass myClass;

    public Stirng methodToBeTested() {
        myClass.doSomethingElse("..");
    }
}

public class class1Test {

    @Mock
    MyService myService;

    @Resource
    @Spy
    @InjectMocks
    MyClass myClass;

    @Resource
    @InjectMocks
    Class1 class1;

    public void setUPTest() {
        MockitoAnnotations.initMocks(this);
    }

    @Test
    public void methodToBeTestedTest() {
        this.setUPTest();
            ...
            class1.methodToBeTested();
    }

}

Here I want to mock "MyService". But MyService is used in "MyClass" and it is used in "Class1" .

I want to initialise "MyClass" and "Class1" using spring.

When I try to run this test, I got the following exception

org.mockito.exceptions.base.MockitoException: Cannot mock/spy class $Proxy79 Mockito cannot mock/spy following: - final classes - anonymous classes - primitive types

Can anyone help me with this?

1
The service is not used by Class1. The direct dependency of Class1 is MyClass. This is the class you should mock to test Class1. Then to test MyClass, you would mock MyService.JB Nizet
Thanks for the reply. Let me put this in more detailed way, "MyService" is an external web service, and I want to mock all the calls to this service where ever it is in my project.rahul

1 Answers

1
votes

You are testing Class1, which only has MyClass as dependency. MyService is irrelevant to this test. You should mock MyClass and test the call to doSomethingElse.

If you wish to test the call to doSomething of MyService, you should write a MyClassTest which mocks the dependency to MyService.