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

问题描述 投票:0回答:1

即使我使用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
 }

}

我在stack overflow上看了所有可能的问题,并翻阅了powermock和mockito文档,但找不到解决这个问题的办法。

unit-testing android-studio kotlin mockito powermock
1个回答
0
投票
@Mock
lateinit var mcontext: Context

mcontext = Mockito.mock(Context::class.java)

是一个太多。使用其中一种或另一种(当然首选注释)。

参见 mocks创建的速记 - @Mock注释:

重要! 这需要在基类或测试运行器中的某个地方。

MockitoAnnotations.initMocks(testClass);

关于你最后的代码评论: 对象是 嘲弄,方法是 矮小.

© www.soinside.com 2019 - 2024. All rights reserved.