【问题标题】:Android Studio - Junit 4 - Running code before ALL testsAndroid Studio - Junit 4 - 在所有测试之前运行代码
【发布时间】:2021-07-22 08:26:59
【问题描述】:
我有一个应用程序,无论何时打开该应用程序,我都想对其强制使用locale。所以我会在应用程序的onCreate()方法中使用Locale.setDefault(myCountryLocale).
单元测试不会启动该类,因此我希望能够在启动测试时设置相同的语言环境。通过扩展程序或 gradle 脚本设置语言环境,以便在运行测试的人使用其他语言环境时测试不会失败。
【问题讨论】:
标签:
android
android-studio
junit
junit4
【解决方案1】:
我知道这是有点旧的帖子,但我遇到了这个问题。
您可以扩展RunListener 类并覆盖testRunStarted,此代码块将在所有测试之前只运行一次。
此侦听器将像这样添加到您的测试清单中
<instrumentation
android:name="androidx.test.runner.AndroidJUnitRunner"
android:targetPackage="YOUR_APP_PACKAGE">
<meta-data
android:name="listener"
android:value="YOUR_LISTENER_PACKAGE" />
</instrumentation>
【解决方案2】:
您可以使用 JUnit 的 TestSuite 来实现。
package com.dinkar.test.sample;
import com.dinkar.test.sample.TestA;
import com.dinkar.test.sample.TestB;
import com.dinkar.test.sample.TestC;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.runner.RunWith;
import org.junit.runners.Suite;
import org.junit.runners.Suite.SuiteClasses;
import java.util.Locale;
/**
* @author dinkark on 29/04/20.
*
*/
@RunWith(Suite.class)
@SuiteClasses({TestA.class, TestB.class, TestC.class})
public class TestSuite {
@BeforeClass
public static void setUp() {
System.out.println("set config required by all the test cases");
System.out.println("This will only run once for all the test case included in TestA ,TestB, TestC");
Locale.setDefault(myCountryLocale);// set your locale
}
@AfterClass
public static void tearDown() {
System.out.println("clean up");
System.out.println("This will also run once only for all the test case included in TestA ,TestB, TestC");
}
}