Ignoring Android device tests based on SDK level

Is there an annotation or some other convenient way to ignore junit tests for certain versions of the Android SDK? Is there something similar to the Lint TargetApi (x) annotation? Or do I need to manually check if a test should be run using the Build.VERSION command?

+6
source share
3 answers

I donโ€™t think there is anything ready, but itโ€™s pretty easy to create a custom annotation for this.

Create your own annotation

@Target( ElementType.METHOD ) @Retention( RetentionPolicy.RUNTIME) public @interface TargetApi { int value(); } 

Flip the test runner (which will check the value and ultimately ignore / run the test)

 public class ConditionalTestRunner extends BlockJUnit4ClassRunner { public ConditionalTestRunner(Class klass) throws InitializationError { super(klass); } @Override public void runChild(FrameworkMethod method, RunNotifier notifier) { TargetApi condition = method.getAnnotation(TargetApi.class); if(condition.value() > 10) { notifier.fireTestIgnored(describeChild(method)); } else { super.runChild(method, notifier); } } } 

and mark your tests

 @RunWith(ConditionalTestRunner.class) public class TestClass { @Test @TargetApi(6) public void testMethodThatRunsConditionally() { System.out.print("Test me!"); } } 

Just tested, it works for me. :)

Credits for: Conditionally ignoring JUnit tests

+9
source

I searched for the answer to this question and did not find a better way than checking the version. I was able to conditionally suppress the execution of test logic by putting a check in the following Android TestCase methods. However, this does not actually prevent the execution of individual tests. Overriding the runTest() method like this will cause the tests to โ€œpassโ€ through API levels that, as you know, will not work. Depending on your test logic, you can also override tearDown() . Maybe someone will suggest a better solution.

 @Override protected void setUp() throws Exception { if (Build.VERSION.SDK_INT < Build.VERSION_CODES.GINGERBREAD) { if (Log.isLoggable(TAG, Log.INFO)) { Log.i(TAG, "This feature is only supported on Android 2.3 and above"); } } else { super.setUp(); } } @Override protected void runTest() throws Throwable { if (Build.VERSION.SDK_INT < Build.VERSION_CODES.GINGERBREAD) { assertTrue(true); } else { super.runTest(); } } 
+2
source

Alternatively, you can use JUnit assume functionality:

 @Test fun shouldWorkOnNewerDevices() { assumeTrue( "Can only run on API Level 23 or newer because of reasons", Build.VERSION.SDK_INT >= 23 ) } 

If applied, it actually marks the test method as skipped.

This is not as good as annotation solution, but you also don't need JUnit custom test runner.

0
source

Source: https://habr.com/ru/post/949464/


All Articles