测试功能test_init_1()
成功,但是test_init_2()
失败
这是因为MyService
已被初始化。
@RunWith(RobolectricTestRunner::class)
class TrackingServiceInitTest {
@Test
fun test_init_1() {
val result = MyService.init(context, id1)
assertTrue(result) // result = `true`
}
@Test
fun test_init_2() {
val result = MyService.init(context, id2)
assertTrue(result) // AlreadyInitialized Exception has thrown!
}
@After
fun tearDown() {
// what should I do here to clear MyService's state?
}
}
MyService如下:
public class MyService {
public static synchronized boolean init(Context context) {
if (sharedInstance != null) {
Log.d(TAG, "Already initialized!");
throw new AlreadyInitialized();
}
// initializing..
sharedInstance = new CoreService();
return true
}
}
如何清除这种状态?
答案 0 :(得分:1)
正确的解决方案是在标记为MyService
的{{1}}上添加一个静态方法,该方法会释放@VisibleForTesting
:
sharedInstance
然后在您的public class MyService {
public static synchronized boolean init(Context context) {
if (sharedInstance != null) {
Log.d(TAG, "Already initialized!");
throw new AlreadyInitialized();
}
// initializing..
sharedInstance = new CoreService();
return true;
}
@VisibleForTesting
public static void destroy() {
sharedInstance = null;
}
}
中致电tearDown
。