Mockito 3 mock method of an autowired class

Viewed 484

I'm using spring-boot-starter-test 2.2.0 which includes Mockito 3.1.0.

I would like to test this class:

@RestController
public class MyClass {
    @Autowired MyAutowired myAutowired;

    public int myClassMethod(int i) {
        return myAutowired.methodToMock(i);
    }
}

Which use this one:

@Service
public class MyAutowired {

    public int methodToMock(int i) {
        return i;
    }
}

In my test I would like to run myClassMethod but with a mocked behavior for methodToMock. Ideally I would like to check if methodToMock was called with the expected argument.

Here is what I tried so far:

@SpringJUnitConfig(Config.class)
@WebAppConfiguration
@ExtendWith(MockitoExtension.class)
class MyClassTest {
    @Autowired MyClass myClass;

    @Mock
    private MyAutowired myAutowired;

    @BeforeEach
    public void initMocks(){
        MockitoAnnotations.initMocks(this);
    }

    @Test
    public void myTest() {
        Mockito.when(myAutowired.methodToMock(any()).thenReturn(1);

        int shouldBe1ButIs2 = myClass.myClassMethod(2);
    }

}

What's wrong with that ? And how to make myClass.myClassMethod(2) return 1 ?

1 Answers

The issue is that your object MyClass is not referring to the right mock instance. The MyAutowired has to injected into MyClass.

You have two options:

  1. Creating a setMyAutowired method in MyClass and pass the MyAutowired instance to it in your test class.
  2. Replacing @Autowired with @InjectMocks annotation on MyClass. In this way, an instance of MyClass will be created and mocks objects which you declared in your test will be injected automatically in it.

I normally use the second option, which is more elegant.

Related