【发布时间】:2016-02-04 14:33:44
【问题描述】:
我搜索了 SO,发现了一堆看起来相似但不完全相同的其他问题,所以我会再问一个。
我有 Spring 应用程序并说我创建了自定义方面(寻找 CatchMe 注释)以特定方式记录异常。我想通过模拟我的 Spring @Service 类方法之一的行为来测试方面,以便在调用它时抛出异常。然后在另一种方法中,使用我的自定义注释@CatchMe 进行注释,我调用第一种方法。我期望发生的是被记录的异常。不幸的是,抛出了异常,但没有触发方面。那么如何使用 Mockito 在此测试中触发方面?
注意:我已经检查了这些(以及更多):
- Unit testing Spring @Around AOP methods
- Spring Aspect not triggered in unit test
- Spring: cannot inject a mock into class annotated with the @Aspect annotation
但其中大多数是与控制器相关的,而不是与服务相关的,我只想测试服务。
测试
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = {BeanConfig.class})
public class MyServiceTest {
@Autowired
@InjectMocks
private MyService service;
@Mock
private MyServiceDependency serviceDep;
@Before
public void setUp() throws Exception {
MockitoAnnotations.initMocks(this);
ReflectionTestUtils.setField(service, "serviceDep", serviceDep);
}
@Test
public void test() {
when(serviceDep.process()).thenAnswer(new Answer<Object>() {
@Override
public Object answer(InvocationOnMock invocationOnMock) throws Throwable {
throw new Exception("Sample message.");
}
});
service.execute();
}
}
服务
@Service
public class MyService {
@Autowired
private MyServiceDependency serviceDep;
@CatchMe
public void execute() {
serviceDep.process();
}
}
@Service
public class MyServiceDependency {
public Object process() {
// may throw exception here
}
}
配置和方面
@Configuration
@EnableAspectJAutoProxy
@ComponentScan(basePackages = {"com.example.services"})
public class BeanConfig { .. }
@Aspect
@Component
public class CatchMeAspect {
@Around("@annotation(CatchMe)")
public Object catchMe(final ProceedingJoinPoint pjp) throws Throwable {
try {
pjp.proceed();
} catch (Throwable t) {
// fency log
}
}
}
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface CatchMe {}
编辑:该功能有效,但我想通过测试对其进行验证。
【问题讨论】:
-
如果只是重试,您想使用
spring-retry而不是重新发明轮子。为什么你的测试类是@Configuration所有注释什么都不做,因为它不是基于弹簧的测试类。你应该有@ContextConfiguration和@RunWith(SpringJUnit4Runner.class)让 spring 做事。 -
还有一个事实是控制器或其他无关紧要的东西(至少对于单元测试而言)。
-
是的,你是对的。我弄乱了样本。让我修复它。关于控制器与服务 - 如果您检查答案,建议的修复是使用
MockMvcBuilders构建用于调用控制器的MockMvc。这不适用于我的情况。 -
@M.Deinum 现在怎么样?
-
如前所述,我提到的是单元测试而不是集成/系统测试!但随后我们讨论的是定义,而不是您的问题。
标签: java spring testing mockito aop