Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring & Mockito - ignore transitive dependencies

I have a layered application that looks like this:

@PreAuthorize('isAuthenticated()')
@Controller
public class MyController {
    @Autowired
    MyService service;
}

@Service 
public class MyService {
    @Autowired
    MyDao dao;
}

public interface MyDao {
}

@Repository
public class MyDaoImpl implements MyDao {
}

I want to test the AOP-dependent @PreAuthorize annotation, so I use the SpringJUnit4ClassRunner which creates a test AuthenticationManager and MyController.

If the @ContextConfiguration does not include any bean matching MyService, test initialization fails because it can't resolve the bean.

If I didn't need AOP, I would use Mockito test runner and inject Mockito.mock(MyService.class). But if I try and do it with spring runner, again my test fails because it can't resolve MyDao for the service (even though the service a mock).

I definitely don't want to mock the whole object graph. I'd rather it stopped on the mocked service. How can I do it?

like image 720
Konrad Garus Avatar asked Dec 30 '25 20:12

Konrad Garus


1 Answers

Your MyService should implement an interface, and you should mock the interface instead of the class. Then you won't need a DAO implementation. You might also, perhaps, be running into a similar issue that I faced while trying to test a JAX-RS resource class in Jersey. The problem is how to deploy a single bean into a Spring container but mock its dependencies. I wrote a blog post on it that might help you out if this is the problem you're facing. In particular, the final solution may be of help.

like image 109
Ryan Stewart Avatar answered Jan 02 '26 13:01

Ryan Stewart



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!