Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

android unit test spannablestringbuilder

One of my classes uses SpannableStringBuilder and I need to write unit test code for it. This class is for general use and does not interact with any UI components. I considered it as a local unit test but Android Studio complains that 'unit test not mocked'. I've checked Android Mock and robolectric but I can't figure out which instrumentation I have to mock. I also tried putting the test under the AndroidTest directory and ran it as an instrumentation test but still got an error 'Class not found: "....." Empty test suit'.

The unit test code:

package xxxxxxx;  // Sorry but I should keep it secret now.

import android.support.test.filters.SdkSuppress;
import android.test.suitebuilder.annotation.SmallTest;
import android.text.SpannableString;
import android.support.test.runner.AndroidJUnit4;

import org.junit.Test;
import org.junit.runner.RunWith;

import xxxxxxx.HtmlParser;

import static org.junit.Assert.*;

@RunWith(AndroidJUnit4.class)
@SdkSuppress(minSdkVersion=16)
@SmallTest
public class HtmlParserTest {
    @Test
    public void TestGetHtml() {
        // assertion goes here
    }

    @Test
    public void TestGetPlainText() {
        // assertion goes here
    }
}
like image 977
mljli Avatar asked Oct 15 '25 14:10

mljli


1 Answers

I don't know if it was because I did something wrong. Eventually I got it work and I'll post the solution here for your reference.

As metioned in my question, this unit test should run on an Android device or an emulator. So the first thing to do is moving it into the androidTest directory. Only in this way will Android Studio recognize it as an instrumentation test. Also remember to update your app's gradle.build as described here. But Android Studio (Mine is v2.1) won't allow you to run this test directly (as least I couldn't). You have to create a test suite which looks like:

package xxxxxxx.htmltestsuite;

import org.junit.runner.RunWith;
import org.junit.runners.Suite;


@RunWith(Suite.class)
@Suite.SuiteClasses({
    HtmlParserTest.class
})

// place holder class
public class HtmlTestSuite {}
like image 194
mljli Avatar answered Oct 18 '25 06:10

mljli



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!