Solved

No events to be sent to Amplitude with amplitude SDK when running in a junit 5 test unit

  • 11 October 2022
  • 4 replies
  • 190 views

Badge

A very simple code like the following:

Amplitude client = Amplitude.getInstance();
client.init(".....");
Event e = new Event("TestEvent","TestUser");
client.logEvent(e);
client.flushEvents();
client.shutdown();

The event can be sent to amplitude when I run these code in a java main() method, but cannot in a test unit.

There is no any errors when running a test unit, just cannot see the events in amplitude.  

Is there anything I should concern ?  I notice that the Amplitude SDK use a new Thread to send the event to amplitude, is that related with my issue?

Thanks.

icon

Best answer by Denis Holmes 13 October 2022, 10:32

View original

4 replies

Userlevel 6
Badge +8

Hi @kenny ,

 

I am not entirely sure of the reason for this but you should be able to use it in a JUnit test, unless something is blocking it. Have you run the exact same code in both the JUNit test and the main method? I don’t believe there should be a reason for it to not work. Is the code running? Are there any errors given?

 

Kind Regards,
Denis

Badge

Hi Denis, thanks for your reply. Yes, I run the exact same code in both the junit test and the main method.  No errors in both codes.

I guess it’s related with Amplitude Java SDK. The SDK uses a new Thread to send the events. It seems that the junit test main thread ends before the events are sent to Amplitude. So,  I have resolve the problem, the following codes can send the events to Amplitude now in a junit test:

    @Test
void sendDataToAmplitude_with_callback() throws Exception{
Amplitude client = Amplitude.getInstance();
client.init("apiKeyXXXXXX");
Event e = new Event("TestEvent","TestUser");

var countDownLatch = new CountDownLatch(1);
AmplitudeCallbacks callbacks =new AmplitudeCallbacks(){
@Override
public void onLogEventServerResponse(Event event, int status, String message) {
countDownLatch.countDown();
}
};
client.logEvent(e, callbacks);
client.flushEvents();
countDownLatch.await();
client.shutdown();
}

 

We need to wait for the response.

Userlevel 6
Badge +8

Hi @kenny ,

 

My apologies for my delayed response, I was OOO. Is the event now sending successfully? 

 

Kind Regards,
Denis

Badge

Sorry for the horrible late reply, thanks Denis, yes, it works.

Reply