Spring AOP Aspect not working using Mockito

I have @Aspect which intertwines the execution of all my controller action methods. It works great when I start the system, but not in unit testing. I use Mockito and junit as follows:

 @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration("file:**/spring-context.xml") @WebAppConfiguration public class UserControllerTest { private MockMvc mockMvc; @Mock private RoleService roleService; @InjectMocks private UserController userController; @Before public void setUp() { MockitoAnnotations.initMocks(this); ... mockMvc = MockMvcBuilders.standaloneSetup(userController).build(); } ... } 

with some @Test using mockMvc.perform() .

And my aspect:

 @Pointcut("within(@org.springframework.stereotype.Controller *)") public void controller() { } @Pointcut("execution(* mypackage.controller.*Controller.*(..))") public void methodPointcut() { } @Around("controller() && methodPointcut()") ... 
+7
source share
2 answers

First you need to use webAppContextSetup, as Jason suggested:

 @Autowired private WebApplicationContext webApplicationContext; @Before public void setUp() throws Exception { ... mockMvc = MockMvcBuilders.webAppContextSetup(webApplicationContext).build(); } 

At this point, the aspect should be launched, but Mockito will not introduce layouts. This is because Spring AOP uses a proxy object and layouts are embedded in this proxy object instead of a proxy object. To fix this, you must expand the object and use ReflectionUtils instead of the @InjectMocks annotation:

 private MockMvc mockMvc; @Mock private RoleService roleService; private UserController userController; @Autowired private WebApplicationContext webApplicationContext; @Before public void setUp() { MockitoAnnotations.initMocks(this); UserController unwrappedController = (UserController) unwrapProxy(userController); ReflectionTestUtils.setField(unwrappedController, "roleService", roleService); mockMvc = MockMvcBuilders.webAppContextSetup(webApplicationContext).build(); } ... public static final Object unwrapProxy(Object bean) throws Exception { /* * If the given object is a proxy, set the return value as the object * being proxied, otherwise return the given object. */ if (AopUtils.isAopProxy(bean) && bean instanceof Advised) { Advised advised = (Advised) bean; bean = advised.getTargetSource().getTarget(); } return bean; } 

At this point, any call to when (...). ThenReturn (...) should work correctly.

This is explained here: http://kim.saabye-pedersen.org/2012/12/mockito-and-spring-proxies.html

+8
source

You are probably using Spring AOP, in which case the bean must be a Spring bean for AOP to work, without using auto-automation in the controller, it completely bypasses the Spring AOP mechanism.

I think the fix should be to simply enter into the controller

  @Autowired @InjectMocks private UserController userController; 
0
source

All Articles