Java – How do I create a new Bundle object?

How do I create a new Bundle object?… here is a solution to the problem.

How do I create a new Bundle object?

I’m trying to use Firebase Analytics for Android apps in order to record the events I’m following https://firebase.google.com/docs/analytics/android/events That is, in order to send my event, I have to create a new Bundle object (which I created using the default constructor) and call Firebase Analytics’ logEvent function. While testing my development with simple unit tests, I realized that there was no content set in the bundle, which made me wonder if any information was sent. By the way, it also broke my test case.

Here is a simplified test case showing my problem:

import android.os.Bundle;
import org.junit.Test;

import static junit.framework.Assert.assertEquals;

public class SimpleTest {

@Test
    public void test() {
        Bundle params = new Bundle();
        params.putString("eventType", "click");
        params.putLong("eventId",new Long(5542));
        params.putLong("quantity", new Long(5));
        params.putString("currency", "USD");

assertEquals("Did not find eventType=click in bundle", "click", params.getString("eventType"));
    }
}

This test case fails with the following message:

junit.framework.ComparisonFailure: Did not find eventType=click in bundle
Expected :click
Actual :null

Does anyone know what the problem is? That is, how do I create a Bundle object from scratch and populate it properly so that I can use it in a unit test like this?

Please bear with me because I’m learning more about the Android environment.

Solution

As Tanis.7x pointed out in his comment to my original question, all Android framework classes need to be mocked because the android .jar used to run unit tests is empty, as documented here .

Here is an updated version of my original simplified test case :

import android.os.Bundle;

import org.junit.Test;
import org.mockito.Mockito;

import static junit.framework.Assert.assertEquals;

public class SimpleTest {

@Test
    public void test() {
        Bundle bundleMock = Mockito.mock(Bundle.class);
        Mockito.doReturn("click").when(bundleMock).getString("eventType");
        Mockito.doReturn(new Long(5542)).when(bundleMock).getLong("eventId");
        Mockito.doReturn(new Long(5)).when(bundleMock).getLong("quantity");
        Mockito.doReturn("USD").when(bundleMock).getString("currency");

assertEquals("Did not find eventType=click in bundle", "click", bundleMock.getString("eventType"));
    }
}

The main difference is that variables I used to set with simple getters are now set using the appropriate functions of mockitos. The code doesn’t look that easy, but it should get me the behavior I want.

Related Problems and Solutions