I am working on unit tests to map an object to an another : this is my test class. The issue is a NPE caused by the first line in GeneratEvent where its supposed to get a randomId(it works if its hardcoded) the wierd thing is you can see that the idGenerator works fine while testing outside that class
public class MessageTest {
@InjectMocks
private IdGeneratorConfig idGenerator;
@Mock
private IKafkaService kafkaService;
@Mock
private IKafkaService kafkaService;
@ExtendWith(MockitoExtension.class)
@InjectMocks
private IngestedEventGenerator ingestedEventGenerator;
@Before
public void setUp() {
MockitoAnnotations.openMocks(this);
}
@Test
public void testGenerateAndSendEventIngestion() {
Message message = new Message();
message.setMsgId(12356486);
message.setCustomId("custom1");
message.setRecipientEmail("exemple@example.com");
message.setMetadata("metadatamail");
long expectedEventId =idGenerator.newIdGenerator().ranId() ;
System.out.println(expectedEventId); // works fine !!!
MessageEvent messageEvent = (MessageEvent) messageEventGenerator.generateEvent(message); // null pointer exception(Id null !!?)
messageEvent.setEventId(expectedEventId);
assert messageEvent != null;
assertEquals(12360055, messageEvent.getMsgId());
assertEquals("custom1", messageEvent.getCustomId());
assertEquals("exemple@example.com", messageEvent.getRecipient());
assertEquals("metadatamail", messageEvent.getMetadata());
messageEventGenerator.sendEvent(messageEvent);
verify(kafkaService, times(1)).sendEvent(messageEvent, "Eve");
}
and this is the class that iam testing : i am mapping a message to an event (MesssageEvent extend Event)
public class MessageEventGenerator implements IEventGenerator {
@Autowired
private IdGeneratorConfig idGenerator;
@Autowired
private IKafkaService kafkaService;
@Override
public void sendEvent(Event event) {
kafkaService.sendEvent(event,"newEvent");
}
@Override
public Event generateEvent(Message message) {
long Id =idGenerator.newIdGenerator().ranId() ; // null pointer exception
MessageEvent messageEvent = new MessageEvent();
messageEvent.setMsgId(message.getMsgId());
messageEvent.setCustomId(message.getCustomId());
messageEvent.setEventId(SnowId);
messageEvent.setMetadata(message.getMetadata());
return messageEvent;
}
@Configuration
public class IdGeneratorConfig {
@Bean
@Scope(value = ConfigurableBeanFactory.SCOPE_SINGLETON)
public IdGenerator idGenerator() {
return new IdGenerator();
}
}
You need to mock both the function that generates the ID and also the interface or the config that is calling the genetrated ID.