我正在按照官方「testing your service」文檔中所述編寫我的NetworkMonitorService
的儀器測試。Android:獲取參考開始儀器測試服務
目前我卡住了,因爲我無法弄清楚如何獲取已啓動的服務的引用,以便將mock注入並聲明行爲。
我的代碼:
@RunWith(AndroidJUnit4.class)
@SmallTest
public class NetworkMonitorServiceTest {
@Rule public final ServiceTestRule mServiceTestRule = new ServiceTestRule();
@Test
public void serviceStarted_someEventHappenedInOnStartCommand() {
try {
mServiceTestRule.startService(new Intent(
InstrumentationRegistry.getTargetContext(),
NetworkMonitorService.class));
} catch (TimeoutException e) {
throw new RuntimeException("timed out");
}
// I need a reference to the started service in order to assert that some event happened
// in onStartCommand()...
}
}
有問題的服務不支持綁定。我認爲,如果我實現了對綁定的支持,然後在測試中使用它,以獲得對該服務可以工作的引用。但是,我不喜歡爲了支持測試用例而編寫產品代碼...
那麼,我該如何測試(儀器測試)一個Service
不支持綁定?
用特殊版本「for tests」替換你的應用程序。通過提供定製儀器測試運行器來完成。嘲笑你的依賴它這個「應用程序測試」。查看詳情http://stackoverflow.com/a/41393275/2711056 – MyDogTom
@MyDogTom,我想過這種方法,但我看不到一種簡單的方法來嘲笑服務的依賴這種方式。你能提供一些代碼示例嗎? – Vasiliy