首页 > 解决方案 > 在看似正确的代码中获取 org.mockito.exceptions.misusing.InvalidUseOfMatchersException

问题描述

我有这样的when电话:

    @Mock
    private MyEventFactory myEventFactory;

    @Mock 
    private MyEvent myEvent;
when(myEventFactory.createMyEvent(anyObject(),anyObject(),anyObject(),anyObject(),anyObject(),anyObject(),anyObject(),anyObject(),anyObject(),anyObject(),anyObject())).thenReturn(myEvent);

但是我得到一个例外

org.mockito.exceptions.misusing.InvalidUseOfMatchersException:
Misplaced argument matcher detected here:
You cannot use argument matchers outside of verification or stubbing.

MyEventFactory 是一个接口

这里可能是什么问题?

标签: mockito

解决方案


你有没有初始化模拟?查看发布的完整代码会有所帮助,但我怀疑您需要调用类似

MockitoAnnotations.initMocks(this);

在你运行你的when声明之前。本文展示了一个示例:https ://howtodoinjava.com/mockito/mockito-mock-initmocks/


推荐阅读