我有一个带有@RunWith(SpringJUnit4ClassRunner.class)
的测试类,用于初始化 mockito:
@Before
public void initMocks() {
MockitoAnnotations.initMocks(this);
}
现在我有一个@Autowired字段来获得方面建议,但无法注入模拟。
我的方面:
@Autowired
private MyMock myMock;
@Around("execution(* xxx.MyService.aspectMethod(..))")
public void process(ProceedingJoinPoint joinPoint) throws Throwable {
myMock.mockMethod();
}
我的测试类:
@RunWith(SpringJUnit4ClassRunner.class)
@EnableAspectJAutoProxy(proxyTargetClass = true)
public class MyTest {
@Autowired
private MyService myService;
@Mock
private MyMock myMock;
@InjectMocks
private MyAspectClass;
@Before
public void initMocks() {
MockitoAnnotations.initMocks(this);
}
public void shouldXXXX() {
doThrow(Exception.class).when(myMock).mockMethod();
myService.aspectMethod();
....
}
...
}
问题是触发的方面与我所嘲笑的不一样。
答案很简单
@InjectMocks
private MyAspectClass;