Created
October 28, 2014 13:36
-
-
Save moea/2af0904e9fe4b09e6d90 to your computer and use it in GitHub Desktop.
Service Instrumentation test
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package me.ambient.cachehours; | |
import android.content.BroadcastReceiver; | |
import android.content.Context; | |
import android.content.Intent; | |
import android.content.IntentFilter; | |
import android.test.ActivityInstrumentationTestCase2; | |
import android.support.v4.content.LocalBroadcastManager; | |
import android.test.ServiceTestCase; | |
import java.util.ArrayList; | |
import java.util.List; | |
import java.util.concurrent.CountDownLatch; | |
import java.util.concurrent.TimeUnit; | |
public class IntentServiceTest extends ServiceTestCase<MyIntentService> { | |
protected CountDownLatch latch; | |
protected LatchBroadcastReceiver receiver; | |
protected List<Intent> receivedIntents; | |
public static class LatchBroadcastReceiver extends BroadcastReceiver { | |
protected CountDownLatch latch; | |
private List<Intent> receivedIntents; | |
public LatchBroadcastReceiver(CountDownLatch latch, List<Intent> receivedIntents) { | |
this.latch = latch; | |
this.receivedIntents = receivedIntents; | |
} | |
@Override | |
public void onReceive(Context context, Intent intent) { | |
receivedIntents.add(intent); | |
latch.countDown(); | |
} | |
public List<Intent> getReceivedIntents() { | |
return receivedIntents; | |
} | |
} | |
public IntentServiceTest() { | |
super(MyIntentService.class); | |
} | |
protected MyIntentService service; | |
@Override | |
public void setUp() throws Exception { | |
super.setUp(); | |
receivedIntents = new ArrayList<Intent>(); | |
latch = new CountDownLatch(1); | |
receiver = new LatchBroadcastReceiver(latch, receivedIntents); | |
LocalBroadcastManager.getInstance(getContext()).registerReceiver( | |
receiver, | |
new IntentFilter() {{ | |
addAction("did the doge"); | |
}}); | |
// this will start the activity, so do it after registering the receiver | |
service = getService(); | |
startService(new Intent("do the doge")); | |
} | |
public void testBroadcastsOnRun() throws InterruptedException { | |
latch.await(1, TimeUnit.MINUTES); | |
assertEquals(receivedIntents.size(), 1); | |
} | |
@Override | |
protected void shutdownService() { | |
try { | |
super.shutdownService(); | |
} catch(Exception e) { | |
e.printStackTrace(); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment