Felipe Mosso
Felipe Mosso

Reputation: 3927

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?

Upvotes: 2

Views: 10168

Answers (2)

Felipe Mosso
Felipe Mosso

Reputation: 3927

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!

Upvotes: 0

cristianorbs
cristianorbs

Reputation: 720

I resolve this problem by using:

@BeforeClass
public static void setUpBeforeClass() throws Exception {
}

and:

@AfterClass
public static void tearDownAfterClass() throws Exception {
}

instead of setUp() and tearDown(). So in your case it would be:

import org.junit.AfterClass;
import org.junit.BeforeClass;
public class BaseTests extends InstrumentationTestCase {

@BeforeClass
protected static void setUp() throws Exception { 
    //do your setUp
    Log.d(TAG, "setUp()");
}

@AfterClass
protected static void tearDown() throws Exception {
    //do your tearDown
    Log.d(TAG, "tearDown()");
}

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

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

The annotations @BeforeClass and @AfterClass assure that it will run only one time before and after the test runs respectively

Upvotes: 2

Related Questions