I use Spring boot and in my aspect class I have two fields which have @Autowired annotation. When I run code then it works fine, but when I run test for this class then these two autowired fields are null.
Can someone tell what I need to do to fix that? I'm sorry for lack of code but today I don't have access to this.
example (from another SO question):
Unit test:
@RunWith(MockitoJUnitRunner.class)
public class CompanyServiceImplTest {
@Test
public void createCampaignTest() throws Exception {
when(companyDaoMock.saveCompany(any(Campaign.class))).thenReturn(77L);
Long campaignId = companyService.createCampaign(campaignMock);
assertEquals(Long.valueOf(77L), Long.valueOf(campaignId));
}
}
Service method:
@Override
@Transactional
@EventJournal(type = EventType.CAMPAIGN_CREATE, owner = EventOwner.TERMINAL_USER)
public Long createCampaign(Campaign campaign) {
return companyDao.saveCompany(campaign);
}
Aspect:
@Aspect
public class EventJournalAspect {
@Autowired
private EventJournalService eventJournalService;
@Pointcut(value="execution(public * *(..))")
public void anyPublicMethod() {}
@Pointcut("within(com.terminal.service..*)")
private void inService() {}
@AfterReturning(pointcut = "anyPublicMethod() && inService() && @annotation(eventJournal) && args(entity,..)", returning = "id")
public void process(Object id, EventJournal eventJournal, AbstractDomainEntity entity)
throws Throwable {
if (eventJournal.type() != EventType.CAMPAIGN_PAYMENT || id != null) {
saveEvent(eventJournal, EventStatus.SUCCESS, entity, (Long) id);
}
}
@AfterThrowing(pointcut = "anyPublicMethod() && inService() && @annotation(eventJournal) && args(entity,..)", throwing="ex")
public void processException(EventJournal eventJournal, AbstractDomainEntity entity, Exception ex) throws Throwable {
saveEvent(eventJournal, EventStatus.FAILURE, entity, null);
}
private void saveEvent(EventJournal eventJournal, EventStatus status, AbstractDomainEntity entity, Long persistentId) {
EventType type = eventJournal.type();
EventOwner owner = eventJournal.owner();
eventJournalService.saveEvent(type, owner, EventStatus.SUCCESS, entity, persistentId);
}
}
When test executes - eventJournalService
is null. Thus I see NullPointerException