Search code examples
javaspringjunitmockitospring-boot-test

@MockBean and @Autowired of the same service in one test class


Is it possible to somehow have in the same test class @MockBean and @Autowired of the same service?

In other words, I would like to have @MockBean service only for one test, while for others tests of the same class I need it as @Autowired.


Solution

  • The best solution is to change @MockBean to @SpyBean. And in the method you will be able to do like this:

    kotlin

        @SpyBean
        lateinit var serviceMock: Service
    
        @Test
        fun smallTest()
            `when`(serviceMock.doSomething())
                .thenReturn(false)
    
            // your test logic
        }