I want to back up my application's database before replacing it with the test fixture. I'm forced to use Junit3 because of Android limitations, and I want to implement the equivalent behavior of @BeforeClass an @AfterClass.
UPDATE: There is now a tool (Junit4Android) to get support for Junit4 on Android. It's a bit of a kludge but should work.
To achieve the @BeforeClass equivalent, I had been using a static variable and initializing it during the first run like this, but I need to be able to restore the database after running all the tests. I can't think of a way of detecting when the last test has run (since I believe there is no guarantee on the order of test execution.)
public class MyTest extends ActivityInstrumentationTestCase2<MainActivity> {
private static boolean firstRun = true;
@Override
protected void setUp() {
if(firstRun) {
firstRun = false;
setUpDatabaseFixture();
}
}
...
}
Similarly function with @After annotation will be executed after each of test function in the class having @Test annotation but the function with @AfterClass will be execute only one time after all the test functions in the class.
@BeforeTest method executes only once before the first @Test method. @BeforeClass executes before each class. If there are separate @BeforeTest and @BeforeClass methods in different classes, then all the @BeforeTest methods will execute first but @BeforeClass methods will be executing as per the respective classes.
The JUnit Team therefore recommends that developers declare at most one @BeforeEach method and at most one @AfterEach method per test class or test interface unless there are no dependencies between the @BeforeEach methods or between the @AfterEach methods.
org.junitAnnotating a public static void no-arg method with @BeforeClass causes it to be run once before any of the test methods in the class. The @BeforeClass methods of superclasses will be run before those of the current class, unless they are shadowed in the current class.
From the junit website:
Wrapped the setUp and tearDown method in the suite.This is for the case if you want to run a single YourTestClass testcase.
public static Test suite() {
return new TestSetup(new TestSuite(YourTestClass.class)) {
protected void setUp() throws Exception {
System.out.println(" Global setUp ");
}
protected void tearDown() throws Exception {
System.out.println(" Global tearDown ");
}
};
}
If you would like to run only one setUp and tearDown for all the testcase, make a suite and add testClass to it and pass the suite object in TestSetup constructor.But I think there is not much usage for this,and in a way it is violating JUnit philosophy.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With