junit 使用AdvertisingIdClient.getAdvertisingIdInfo进行的单元测试得到“IllegalStateException:从你的主线程调用这个会导致死锁”

bttbmeg0  于 2023-10-20  发布在  其他
关注(0)|答案(1)|浏览(119)

使用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的函数?

acruukt9

acruukt91#

简单运行:IO线程上的“AdvertisingIdClient.getAdvertisingIdInfo”。

withContext(Dispatchers.IO) {
    AdvertisingIdClient.getAdvertisingIdInfo()
    
}

相关问题