Giorgio Antonioli
Giorgio Antonioli

Reputation: 16214

Bundle put and get Unit test

I'm trying to make a test that will verify that a value is successfully written on a Bundle.

This is a simple class that will write a boolean value on a Bundle:

public class Coder {
    public void serialize(Bundle bundle, String key, boolean value) {
        bundle.putBoolean(key, value);
    }
}

I want to test the serialize method checking the Bundle passed as parameter after the method call using bundle.getBoolean(String).

I tried with an ArgumentCaptor without success:

Coder coder = mock(Coder.class);
Bundle bundle = mock(Bundle.class);

ArgumentCaptor<Bundle> bundleCaptor = ArgumentCaptor.forClass(Bundle.class);
coder.serialize(bundle, key, expectedValue);
verify(coder).serialize(bundleCaptor.capture(), eq(key), eq(expectedValue));

Bundle mockBundle = bundleCaptor.getValue();
assertEquals(expectedValue, mockBundle.getBoolean(key));

But mockBundle.getBoolean(key) returns false.

If I try to not mock the Bundle, I get this exception at mockBundle.getBoolean(key):

java.lang.RuntimeException: Method getBoolean in android.os.BaseBundle not mocked.

Upvotes: 1

Views: 5210

Answers (1)

Code-Apprentice
Code-Apprentice

Reputation: 83527

I think you make this overly complicated.

public class TestCoder {
    @Test
    public void testSerialize() {
        Coder coder = new Coder();
        Bundle bundle = new Bundle();
        coder.serialize(bundle);
        assertEquals(expectedValue, bundle.getBoolean(key));
    }
}

Upvotes: 2

Related Questions