0

How to add some one time initiation code in robolectric Android tests.

We can add like Some method with @Before annotation which would run before the tests of that class run but can wee add some code that is executed one before any test code is executed, in Android robolectric.

Aamir Abro
  • 838
  • 12
  • 24

2 Answers2

3

Use JUnit's @BeforeClass annotation.

class Test {
    @BeforeClass
    public static void doOnce()
        //Do once before any test case is run.
    }
}
Jocke
  • 414
  • 3
  • 6
0

Solution #1

You can use inheritance or composition. E.g. you can create TestBase class:

class TestBase {
   @Before
   protected setUp() {
      // code for all tests
   }
}

and then your tests can derive from it:

@RunWith(RobolectricTestRunner.class)
class SpecificTest extends TestBase {
   ...
}

Solution #2

You can also create some Utility class containing repeatable code in a method and call this method in every setUp() method in your tests. Then, you won't need inheritance. Example:

class Util {
   private Util() {}
   public static setUp() {
      // code for all tests
   }
}

and your test could look like that:

@RunWith(RobolectricTestRunner.class)
class SpecificTest {
   @Before
   public setUp() {
      Util.setUp();
   }
}
Piotr Wittchen
  • 3,853
  • 4
  • 26
  • 39
  • but would that setUp method run every time that class that extends TestBase is tested? What I want is some event or method that executed just like @before but just once before any tests are executed of any class. – Aamir Abro May 20 '15 at 07:00
  • 1
    @AamirAbro try `beforeTest()` in `TestApplication` that implements `TestLifeCycleApplication`. See http://robolectric.org/custom-test-runner/ – hidro May 21 '15 at 08:50