c 2 c 2 - 1 month ago 32
Android Question

Android Unit test Xml.newSerializer() always return null

I am trying to unit test in Android a class that uses XmlSerializer but for some reason, Xml.newSerializer always returns null. The app code that uses xmlSerializer runs fine though. Does anyone know why it only returns null when unit testing?

import org.junit.Test;
import org.xmlpull.v1.XmlSerializer;

public class TestClass
{
@Test
public void test()
{
XmlSerializer serializer = Xml.newSerializer();
if (serializer == null) {
System.out.println("Is Null!");
}
}
}


The test frameworks I am using are espresso and Mockito. Thanks.

Answer

There are many classes that are provided in the Android platform. Unit tests are run against stubbed versions of these in a library on your computer. They are stubbed in that their methods will return null.

The problem seems to be the Xml.newSerializer() - the stubbed version of Xml will just return null from this method call.

One possible workaround is to run this unit test androidTest instead of in test. You will then have to run the unit test on the device rather than on your computer.

Another option is installing Robolectric. This provides working alternatives to the stubs that will allow you to execute unit tests without using the emulator.