3

When I write spring boot test and define service as following:

@MockBean
@InjectMocks
private Service service;

i got BeanCreationException: Could not inject field ... cannot have an existing value Why ?

Why i cannot have my service mocked and all its autowired fields mocked as well ?

voipp
  • 1,243
  • 3
  • 18
  • 31
  • Why inject something into a mock... That doesn't make sense. – M. Deinum Nov 07 '18 at 11:52
  • @M.Deinum, what if there is a bean `A` which depends on bean `B` and I want to mock method `A#method1` to return a mocked value sometimes and other times I want it to return the real value it would return (which logic depends on a mocked bean `B`)? I'd need to inject into mock `B` into mock `A`. How could that be overcomed? – jbuddy Oct 06 '20 at 09:33
  • You cannot inject a mock into a mock – M. Deinum Oct 06 '20 at 13:44

1 Answers1

6

You are combining plain mockito (@Mock, @InjectMocks) with the spring wrappers for mockito (@MockBean). Please take a look at this explanation: Difference between @Mock, @MockBean and Mockito.mock()

Sven
  • 2,343
  • 1
  • 18
  • 29
  • 1
    this is good one as an addition, if you are using SpringBoot then preferred to use @MockBean, as the bean will be loaded in application context. – Naveen Jun 04 '20 at 06:22