rahul
rahul

Reputation: 393

Unit test in spring using Mockito

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?

Upvotes: 0

Views: 800

Answers (1)

Tom Verelst
Tom Verelst

Reputation: 16002

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.

Upvotes: 1

Related Questions