Android JUnit tests can't call any android api?

后端 未结 1 1810
[愿得一人]
[愿得一人] 2021-01-18 07:55

From Android\'s Testing Fundamentals, \"You can use plain JUnit to test a class that doesn\'t call the Android API, or Android\'s JUnit extensions to test Android components

相关标签:
1条回答
  • 2021-01-18 08:25

    I was running into a similar problem with a SpannableStringBuilder. My problem was solved by moving my test to the androidTest directory. (Thanks to this answer for the suggestion.)

    Here is the test in the new location:

    /**
     * Instrumentation test, which will execute on an Android device.
     *
     * @see <a href="http://d.android.com/tools/testing">Testing documentation</a>
     */
    @RunWith(AndroidJUnit4.class)
    public class ExampleInstrumentedTest {
    
        @Test
        public void myStringTest() throws Exception {
            CharSequence unicode = "";
            MyClass myClass = new MyClass(unicode); 
            CharSequence result = myClass.getUnicodeText(); // uses SpannableStringBuilder internally
            CharSequence expected = unicode;
            assertEquals(expected, result);
        }
    }
    

    Note

    You can also try mocking the Android classes, but this was a lot easier for a Testing beginner like me. The disadvantage, I suppose, is that the instrumentation tests run slower than Unit tests.

    0 讨论(0)
提交回复
热议问题