Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring tries to autowire Mockito mocks

Tags:

spring

I have a spring managed application in which I like for my service layer to be mocked. So I created a Spring Application Java Config and returned a mock of the actual service.

For e.g,

@Bean
@Profile("resource")
public MyService mockService() {
    return mock(MyService.class)
}

And then the MyService goes as

class MyService {

   @Autowired
   private MyDao dao;
}

When Spring creates bean of name "mockService", it also tries to Autowire MyDao on the mock ? This in my opinion defeats the purpose of mocking. Is this the expected behaviour, whats the workaround ?

like image 236
Sathyakumar Seshachalam Avatar asked Oct 30 '22 07:10

Sathyakumar Seshachalam


1 Answers

So bottomline, its best practice to code to interfaces rather than concrete classes particularly if you are wanting to write focused tests on specific layers.

like image 106
Sathyakumar Seshachalam Avatar answered Nov 15 '22 10:11

Sathyakumar Seshachalam