我需要避免在对类进行单元测试时调用某个方面。
我正在使用 Java 8、spring 4.3.22.RELEASE 和mockito。我有一个@Service 和一个单元测试。我还有一个 @Aspect,它在服务中的方法上定义了切入点,并且当我运行我的应用程序时它工作正常。问题是,当我运行单元测试时,会调用该方面,并由于该方面缺少依赖项而引发 NullPointerException。
服务等级:
@Service
public class ContactService {
@Autowired
public InContactService(ContactDao contactDao) {
this.contactDao = contactDao;
}
public boolean muteCall(Long contactId) {
return contactDao.muteCall(contactId);
}
}
服务测试:
public class ContactServiceTest {
@Mock
private ContactDao contactDao;
private ContactService contactService;
@Before
public void setUp(){
MockitoAnnotations.initMocks(this);
contactService = new ContactService(contactDao);
}
@Test
public void testMuteCall(){
contactService.muteCall(1L);
}
}
方面:
@Aspect
public class ContactAspect {
private MeterRegistry registry;
public void setRegistry(MeterRegistry registry) {
this.registry = registry;
}
@AfterReturning(pointcut = "execution(* com.company.ContactService.muteCall(..))", returning = "retVal")
public void checkReturnContactServiceMuteCall(JoinPoint joinPoint, boolean retVal) {
Object[] args = joinPoint.getArgs();
registry.counter("my.metric.mute_call").increment();
}
}
应用背景:
@Configuration
public class ApplicationContext {
@Bean
public MeterRegistry meterRegistry() {
return new SimpleMeterRegistry();
}
@Bean
public ContactAspect contactAspect() {
ContactAspect aspect = Aspects.aspectOf(ContactAspect.class);
aspect.setRegistry(meterRegistry());
return aspect;
}
}
我预计当测试运行时不会调用方面。目前,当我运行测试时,我收到 NullPointerException,因为registry方面未定义。
开心每一天1111
沧海一幻觉
暮色呼如
相关分类