2

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.

1

2 Answers 2

2

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.

1
  • 1
    Thanks. That's what I ended up doing. I used Robolectric.
    – c 2
    Nov 6, 2016 at 5:24
1

You can try using org.xmlpull.v1.XmlPullParserFactory which doesn't depend on Android platform

XmlPullParserFactory factory = XmlPullParserFactory.newInstance();
XmlSerializer serializer = factory.newSerializer();

just make sure you add testImplementation 'net.sf.kxml:kxml2:2.3.0' to the dependencies in build.gradle

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.