Unit testing 无法使用POWERMOCK和mockito模拟私有方法

Unit testing 无法使用POWERMOCK和mockito模拟私有方法,unit-testing,android-studio,kotlin,mockito,powermock,Unit Testing,Android Studio,Kotlin,Mockito,Powermock,即使在使用spy方法时,我也无法模拟attributesStorage()的getContext()方法来获取上下文。 这是我的代码: class Rich { fun method1() : HashMap<String,String> { val x = attributeStorage().getStore() return x } } class AttributeStorage { private f

即使在使用spy方法时,我也无法模拟attributesStorage()的getContext()方法来获取上下文。 这是我的代码:

class Rich
{
    fun method1() : HashMap<String,String>  
    {
        val x = attributeStorage().getStore()
        return x
    }

}

class AttributeStorage
{

    private fun getContext()
    {
        return MyProject.instance.context() 
    }

    fun getStore()
    {
        //some work done,   
        return HashMap<String,String>()
    }
}

@PrepareForTest(Rich::class)
class RichTest {

    @Mock
    lateinit var mcontext: Context


 fun init()
    {
        mcontext = Mockito.mock(Context::class.java)
        val mAttributesStorage = spy(AttributesStorage())
        `when`<Context>(mAttributesStorage,"getContext").thenReturn(mcontext)
        Mockito.`when`(mAttributesStorage.getStore()).thenReturn(mapOf("1" to "1"))

    }
 fun test()
 {
     //gives an error because the getContext() couldn't be mocked
 }

}

类丰富
{
fun method1():HashMap
{
val x=attributeStorage().getStore()
返回x
}
}
类属性范围
{
private fun getContext()
{
返回MyProject.instance.context()
}
趣味商店()
{
//做了一些工作,,
返回HashMap()
}
}
@PrepareForTest(富::类)
类别丰富性测试{
@嘲弄
lateinit var mcontext:上下文
fun init()
{
mcontext=Mockito.mock(Context::class.java)
val mAttributesStorage=spy(AttributesStorage())
`当`(mAttributesStorage,“getContext”)。然后返回(mcontext)
Mockito.`when`(mAttributesStorage.getStore())。然后返回(mapOf(“1”到“1”))
}
趣味测试()
{
//给出错误,因为无法模拟getContext()
}
}
我查看了有关堆栈溢出的所有问题,并查看了powermock和mockito文档,但找不到解决此问题的方法。

@Mock
lateinit var mcontext:上下文

mcontext=Mockito.mock(Context::class.java)
太多了。使用一个或另一个(当然,首选注释)

见:

重要这需要在基类或测试运行程序中的某个位置:

MockitoAnnotations.initMocks(testClass)


关于您的上一条代码注释:对象被模拟,方法被存根。

嘿,它仍然不能解决我的错误,我得到的错误是“lateint正确上下文尚未初始化”@coder是您的
init()
方法执行了还是注释丢失了?
test()
方法在没有注释的情况下运行,因为这是Junit的残余。是的,我的init正在执行!我也放了注解!