使用 ShadowGoogleApiAvailability 的 Android 应用程序
object Util {
@JvmStatic
@WorkerThread
fun getAdsClientInfo(context: Context): AdvertisingIdClient.Info? {
val isGPAvailable =
GoogleApiAvailability.getInstance().isGooglePlayServicesAvailable(context)
return if (isGPAvailable == ConnectionResult.SUCCESS) {
AdvertisingIdClient.getAdvertisingIdInfo(context) //<=== throws
} else null
}
}
在测试中:
@RunWith(RobolectricTestRunner.class)
public class TestAds{
public Application application;
@Before
public void setUp() throws Exception {
application = ApplicationProvider.getApplicationContext();
}
@Test
public void test_getAdsClientInfo() throws Exception {
final ShadowGoogleApiAvailability shadowGoogleApiAvailability
= Shadow.extract(GoogleApiAvailability.getInstance());
final int expectedCode = ConnectionResult.SUCCESS;
shadowGoogleApiAvailability.setIsGooglePlayServicesAvailable(expectedCode);
AdvertisingIdClient.Info info = Util.getAdsClientInfo(application);
......
}
}
它得到了
"IllegalStateException: Calling this from your main thread can lead to deadlock"
。
如何测试内部调用
AdvertisingIdClient.getAdvertisingIdInfo
的函数?
简单运行:IO 线程上的“AdvertisingIdClient.getAdvertisingIdInfo”。
withContext(Dispatchers.IO) {
AdvertisingIdClient.getAdvertisingIdInfo()
}