Как очистить статус метода stati c во время теста junit - PullRequest
0 голосов
/ 18 марта 2020

Тестовая функция 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 Ответ

1 голос
/ 18 марта 2020

Правильным решением было бы добавить метод c stati к MyService, помеченному @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 вы можете вызвать MyService.destroy().

...