Unit testing with Android XmlPullParser on the JVM
Asked Answered
B

2

6

I'm trying to set-up unit test cases for my application.

A critical part of the app parses XML files with org.xmlpull.v1.XmlPullParser. As this part is low-level, isolated and independant from activities, context, views, etc., I really wanted to make it run locally on the JVM, to avoid having to plug or emulate a device all the time.

However when running something like this on the JVM:

XmlPullParser parser = Xml.newPullParser();
parser.setInput(in, null);
...

I get the famous:

Exception in thread "main" java.lang.RuntimeException: Stub!
    at android.util.Xml.newPullParser(Xml.java:15)
    ...

Is there a way around this?

Biarritz answered 7/7, 2015 at 15:19 Comment(0)
B
2

I managed to go around this problem by using Robolectric in Android-Studio. I followed this tutorial, and stumbled upon this other problem.

Now it works fine except I can't see the standard output when running tests.

Biarritz answered 8/7, 2015 at 8:42 Comment(0)
C
0

Just like previous comment, I think Robolectric is the way to go.

I think a code sample could be the welcome so here is mine:

Add the dependancy to you build.gradle : If you're using android support lib : testImplementation 'org.robolectric:robolectric:3.8' (AndroidX starts at 4.0)

For other versions : https://mvnrepository.com/artifact/org.robolectric/robolectric

Then in test : (This is Kotlin btw)

@RunWith(RobolectricTestRunner::class)
class XmlParserRelTest {
  private lateinit var xmlParserClass : XmlParserClass 

  @Before
  internal fun setUp() {
      xmlParserClass = XmlParserRel(Xml.newPullParser())
  }

  @Test
  fun validFile_parseRelFile_contentIsPresent() {
      val inputStream = getFileInputStream("test.xml")

      val xmlOutput = xmlParserClass.parseRelFile(inputStream )
    
      assertThat(xmlOutput.attribute1).isEqualTo("something")
  }
}
Candlelight answered 19/10, 2021 at 14:1 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.