简体   繁体   中英

JUnit 4 annotations not working when extending AndroidTestCase class

Hello I am doing the testing section for my sqlite db. I have used JUnit before but I learned I have to extend AndroidTestCase to get a mock context. However, when I try to catch exceptions (like in JUnit) the compiler is complaining. Why is this since Android ships with JUnit 4 now?

class example for reference:

public class MyTest extends AndroidTestCase {

   @Test(expected=NullPointerException.class) //<-- this does not work
   public void testRandomMethod() {
     callRandomMethod()  //Throws NullPointerException
   }
}
  1. Remove AndroidTestCase
  2. Use @Runwith(AndroidJunit4.class)

For context, Use InstrumentationRegistry.getTargetContext() .

If you extend AndroidTestCase then your test is considered to be a JUnit 3 test, because it extends JUnit's TestCase class. Don't extend AndroidTestCase if you're writing a JUnit 4 test.

Basically, your minimal setup for JUnit4 tests should be like this.

  • build.gradle

testCompile 'junit:junit:4.12'

testCompile 'org.hamcrest:hamcrest-core:1.3'

  • add a test to src/test/java folder
  • the simplest test will look like this
public class ExceptionExpectationTest {

    @Test(expected=NullPointerException.class)
    public void shouldThrowException() throws Exception {
        callRandomMethod();
    }

    private static void callRandomMethod() {
        //test will fail because we do not throw NPE
    }
}

PS. For more information take a look at these projectes ( android-testing-templates and qualitymatters ). They have pure junit tests among other types of tests.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM