Using Robolectric, how to init and finalize stuff before and after all test methods in a test class is ran

2.5k views Asked by At

I'm using Robolectric to do unit testing. I have a test class say MainActivityTest, which has several test methods:

@RunWith(...)
@Config(...)
public class MainActivityTest {
    @Test
    public void testMethod1() {
        //...
    }

    @Test
    public void testMethod2() {
        //...
    }

    // other test methods
}

I want to execute a method(init method) only once before any test method is executed, and another method after all test methods are executed. How can I do that? I know I can solve the first question by calling the init method in the constructor, but how can I solve the second question? I know that I can subclass my Application class and use that Application, But that's kind of awkward for me since I'm using AndroidAnnotations and the real Application class I'm using is final, and I only want to do this in this test class, rather than all test class. I wonder if there is better way to do this.

1

There are 1 answers

1
Alex Florescu On BEST ANSWER

You want @BeforeClass and @AfterClass.

Note that the methods they annotate have to be static.

See:

http://junit.sourceforge.net/javadoc/org/junit/BeforeClass.html http://junit.sourceforge.net/javadoc/org/junit/AfterClass.html

So for example:

@BeforeClass
public static void beforeEverything() {
    // runs just once before all tests
}

@Before
public void setup() {
    // runs before every test
} 

@After
public void breakdown() {
    // runs after every test
}

@AfterClass
public static void afterEverything() {
    // runs just once after all the tests
}