Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ignoring Android unit tests depending on SDK level

Tags:

android

junit

Is there an annotation or some other convenient way to ignore junit tests for specific Android SDK versions? Is there something similar to the Lint annotation TargetApi(x)? Or do I manually have to check whether to run the test using the Build.VERSION?

like image 916
Markus K Avatar asked Jul 15 '13 12:07

Markus K


2 Answers

I don't think there is something ready but it pretty easy to create a custom annotation for this.

Create your custom annotation

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

Ovverride the test runner (that will check the value and eventually ignore/fire 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 to: Conditionally ignoring JUnit tests

like image 55
Enrichman Avatar answered Nov 15 '22 11:11

Enrichman


An alternative is to use JUnit's 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, this effectively marks the test method as skipped.

This is not so nice like the annotation solution, but you also don't need a custom JUnit test runner.

like image 35
Thomas Keller Avatar answered Nov 15 '22 13:11

Thomas Keller