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.

Maciej Kowalski
  • 25,605
  • 12
  • 54
  • 63
c 2
  • 1,127
  • 3
  • 13
  • 21
  • Need more context of when it is returning null. provide a [mcve] that reproduces the issue – Nkosi Nov 01 '16 at 16:16

2 Answers2

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.

David Rawson
  • 20,912
  • 7
  • 88
  • 124
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

valka
  • 116
  • 4