开发者

Spring & Mockito - ignore transitive dependencies

开发者 https://www.devze.com 2023-03-21 03:37 出处:网络
I have a layered application that looks like this: @PreAuthorize(\'isAuthenticated()\') @Controller public class MyController {

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 bea开发者_StackOverflown 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?


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消