在junit测试期间如何清除静态方法状态

时间:2020-03-18 08:40:52

标签: android junit robolectric

测试功能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
    }
}

如何清除这种状态?

1 个答案:

答案 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

相关问题