@RunWith(AndroidJUnit4.class) vous permet d'utiliser le contexte Android
/**
* Instrumented test, which will execute on an Android device.
*
* @see <a href="http://d.android.com/tools/testing">Testing documentation</a>
*/
@RunWith(AndroidJUnit4.class)
public class ExampleInstrumentedTest {
@Test
public void useAppContext() {
// Context of the app under test.
Context appContext = InstrumentationRegistry.getInstrumentation().getTargetContext();
assertEquals("com.android.systemui", appContext.getPackageName());
}
}
Vous pouvez même l'exécuter sur le fil principal en utilisant runOnMainSync
. Voici la solution complète :
@RunWith(AndroidJUnit4::class)
class AwesomeViewModelTest {
@Test
fun testHandler() {
getInstrumentation().runOnMainSync(Runnable {
val context = InstrumentationRegistry.getInstrumentation().targetContext
// Here you can call methods which have Handler
})
}
}
0 votes
Pourquoi ne pouvez-vous pas simplement utiliser InstrumentationTestCase ?
1 votes
Parce que je teste les services, pas l'interface utilisateur.
1 votes
Il y a une meilleure réponse ici : [Utiliser AndroidTestCase au lieu d'un test JUnit][1] [1] : stackoverflow.com/questions/3170706/