Search code examples
androidtestingautomated-testsandroid-instrumentation

run setUp() and tearDown() methods for each test suite InstrumentationTestCase Android


I'm implementing a Test automation tool and I have a class which extends InstrumentationTestCase. For example:

public class BaseTests extends InstrumentationTestCase {

    @Override
    protected void setUp() throws Exception {
        super.setUp();
        Log.d(TAG, "setUp()");
    }

    @Override
    protected void tearDown() throws Exception {
        super.tearDown();
        Log.d(TAG, "tearDown()");
    }

    public void test_one() {
        Log.d(TAG, "test_one()");
    }

    public void test_two() {
        Log.d(TAG, "test_two()");
    }
}

When I run the tests of BaseTests, the setUp() method is called 2 times. One time before executing test_one() and another after test_two(). The same happens with the tearDown(), it is called after executing each of both two methods.

What I would like to do here is to call setUp() and tearDown() methods only one time for the execution of all BaseTests tests. So the order of the method call would be like:

1) setUp()

2) test_one()

3) test_two()

4) tearDown()

Is there a way to do such thing?


Solution

  • I ended up following the idea of @beforeClass and @afterClass.

    However I couldn't use the annotations itself. Instead, I implemented them (by using counters) on a base class and my test suites inherits from this base class.

    Here's the link I based myself to do so:

    https://android.googlesource.com/platform/frameworks/base/+/9db3d07b9620b4269ab33f78604a36327e536ce1/test-runner/android/test/PerformanceTestBase.java

    I hope this could help someone else!