如何模拟系统类进行类型转换

时间:2019-06-29 14:04:41

标签: android junit mockito android-testing mockito-kotlin

我有以下代码来获取当前系统内存:

val memClass = (context.getSystemService(Context.ACTIVITY_SERVICE) as ActivityManager).memoryClass

我的最初目标是在测试中为其返回一个Int值。像这样:

whenever((context.getSystemService(Context.ACTIVITY_SERVICE) as ActivityManager).memoryClass)
.thenReturn(500)

由于它是jUnit测试,并且涉及使用Context,因此我最终对所有内容进行了模拟:

val context: Context = mock()

val activityService: Service = mock()

whenever(context.getSystemService(Context.ACTIVITY_SERVICE))
            .thenReturn(activityService)

whenever((context.getSystemService(Context.ACTIVITY_SERVICE) as ActivityManager).memoryClass)
            .thenReturn(500)

现在问题是Mockito无法为ActivityManager创建类型转换并抛出此错误:

java.lang.ClassCastException: android.app.Service$MockitoMock$594525704 cannot be cast to android.app.ActivityManager

我还尝试了模拟ActivityManager,但不能用作类型转换:

enter image description here

对于当前的解决方案,我没有具体要求。我将为实现最初的目标提供更好的方法。

1 个答案:

答案 0 :(得分:1)

也许我们有一个误会。我在说的是这样的:

val context: Context = mock()

val activityService: ActivityManager = mock()

whenever(context.getSystemService(Context.ACTIVITY_SERVICE))
            .thenReturn(activityService)

whenever((context.getSystemService(Context.ACTIVITY_SERVICE) as ActivityManager).memoryClass)
            .thenReturn(500)

据我了解: context.getSystemService(...)返回一个对象。

android.app.ActivityManager和android.app.Service类之间没有关系。


编辑:

最后一行可能需要用等价的
代替(给定的代码可能不是正确的kotlin语法)

    when(activityService.memoryClass).thenReturn(500);