我有一个@Aspect
它编织了我所有控制器操作方法的执行。当我运行系统时它工作得很好,但在单元测试中却不行。我按以下方式使用 Mockito 和 junit:
@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();
}
...
}
和一些@Test
using mockMvc.perform()
.
而我的看点是:
@Pointcut("within(@org.springframework.stereotype.Controller *)")
public void controller() { }
@Pointcut("execution(* mypackage.controller.*Controller.*(..))")
public void methodPointcut() { }
@Around("controller() && methodPointcut()")
...
首先,需要按照 Jason 的建议使用 webAppContextSetup:
@Autowired
private WebApplicationContext webApplicationContext;
@Before
public void setUp() throws Exception {
...
mockMvc = MockMvcBuilders.webAppContextSetup(webApplicationContext).build();
}
此时应该触发切面,但 Mockito 不会注入模拟。这是因为 Spring AOP 使用代理对象,并且模拟被注入到该代理对象而不是被代理对象。要解决此问题,需要解开对象并使用 ReflectionUtils 而不是 @InjectMocks 注释:
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;
}
此时,任何对when(...).thenReturn(...) 的调用都应该正常工作。
这里解释一下:http://kim.saabye-pedersen.org/2012/12/mockito-and-spring-proxies.html http://kim.saabye-pedersen.org/2012/12/mockito-and-spring-proxies.html
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)