如何使用Mockk模拟接口实例

问题描述

具有定义为:

的接口
public interface EventListener {
    void onEvent(String evt);
}

在内联实例化的地方:

// a singleton object
class EventLoger {
    public EventListener listener;
    void registerListener(EventListener l) {
        listener = l;
    }
    void doLog(String evt) {
        listener.onEvent(evt);
    }
...
}

class TheManager () {
    public void setup() {
        EventLoger.getInstance(context).registerListener(new EventListener() {
            @Override
            public onEvent(String evt) {
                //......
            }
        }
    }

    public void doSomeThing(String str) {
        ...
        EventLoger.getInstance(context).doLog(str);
    }
......
}

想做verify { theEvtListener.onEvent(refEq("test")) },如何使用mockk模拟new EventListener()的这个实例?

试图做:

@Test
    fun test_WhenOnEventIsCalled() {
       
        // not sure how to mock the lisnter

        //val evtLisnter: EventListener = mockk(). //??????
        //every {} return theEvtListener. // ???

        val mgr = mockk<TheManager>()
        
        mgr.setup()
        mgr.doSomeThing("test") // it will call the listener.onEvent("test")
        
        verify { theEvtListener.onEvent(refEq("test")) }
    }

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)