Reputation: 1337
The test function test_init_1()
succeed, but test_init_2()
fails
That is because MyService
has been already initialized.
@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 looks like:
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
}
}
How can I clear such status?
Upvotes: 0
Views: 464
Reputation: 16214
The right solution would be adding a static method to MyService
marked with @VisibleForTesting
which releases 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;
}
}
And then in your tearDown
you can call MyService.destroy()
.
Upvotes: 1