2013-06-03 52 views
7

我有一個@Aspect編織我所有的控制器操作方法的執行。它運行良好,我運行系統,但不是在單元測試()。我使用的的Mockito的junit在如下因素的方法:春天的AOP方面不工作使用Mockito

... 

    @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使用mockMvc.perform()

我的看點是:

@Pointcut("within(@org.springframework.stereotype.Controller *)") 
public void controller() { } 

@Pointcut("execution(* mypackage.controller.*Controller.*(..))") 
public void methodPointcut() { } 

@Around("controller() && methodPointcut()") 
... 
+0

我有同樣的問題。我注意到,如果使用替代的''''''''''''''''''''''''''''而不是''standaloneSetup'',但在這種情況下,模擬不會被注入到控制器。我還沒有弄清楚如何讓這兩個工作 –

回答

0

您可能正在使用Spring AOP的,在這種情況下,豆必須是一個Spring bean AOP的工作,通過在控制器不自動裝配它繞過春AOP機制。

我想修補程序應該是簡單地在控制器

@Autowired 
@InjectMocks 
private UserController userController; 
+0

看看代碼示例。 OP已經在按照你的建議進行。 –

+0

是的,錯過了示例中的@Autowire註解,我現在已經將它添加到 –

8

我有同樣的問題注入,這是我做了什麼。

首先,它必須使用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; 
} 

在這點時(...)thenReturn(...)應能正常工作的任何呼叫。

這裏解釋:http://kim.saabye-pedersen.org/2012/12/mockito-and-spring-proxies.html

+2

不錯!我使用泛型來返回一個打印對象......即' T unwrapProxy(T bean)' –