0

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?

2
  • 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. Commented Mar 22, 2013 at 7:20
  • 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. Commented Mar 22, 2013 at 7:26

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Also, the exception that Mockito throws should not occur with the code you have provided. Perhaps if you could post the original code, we can see what is causing the exception.
I am using spring MVC in the above stated scenario. So it has an interface and its impl. I tried mocking MyClass in Class1, since I wanted to initialise using spring "@InjectMocks" and "@Resource" are not working when kept on same variable. Spring initialises first using "@Resource" then "@InjectMocks" is not injecting any mocks into Class1. Will there be any issue if I use spring with mockito?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.