【问题标题】:when() requires an argument which has to be 'a method call on a mock'when() 需要一个参数,该参数必须是“模拟的方法调用”
【发布时间】:2014-08-12 19:20:26
【问题描述】:

我正在测试一个 Spring 服务,我想创建一个使用模拟会话,这样我就不必连接到实际的数据库。

不幸的是:

org.mockito.exceptions.misusing.MissingMethodInvocationException: 
when() requires an argument which has to be 'a method call on a mock'.

TweetServiceTest.java

Session session;
TweetService tweetService = new TweetServiceImpl();

@Before
public void setUp() throws Exception {
    session = Mockito.mock(Session.class);
    HibernateUtil hibernateUtil = Mockito.mock(HibernateUtil.class);
    Mockito.when(hibernateUtil.getSession()).thenReturn(session);
}

HibernateUtil.java

public static Session getSession() {
    Session session = null;
    try {
        session = HibernateUtil.getSessionFactory().getCurrentSession();
        if (!session.isOpen()) {
            session = HibernateUtil.getSessionFactory().openSession();
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
    return session;
}

【问题讨论】:

    标签: hibernate mockito spring-test


    【解决方案1】:

    Mockito 不模拟静态方法。只有实例方法。

    模拟静态方法需要重新定义类本身。

    模拟实例方法只需要创建一个动态生成的子类的实例,它会覆盖超类的所有方法。

    使您的方法成为实例方法(最好),或使用 PwerMockito,AFAIK 允许模拟静态方法(但更复杂和更慢)

    【讨论】:

    • 啊,我明白了,这就解释了。
    猜你喜欢
    • 2017-05-08
    • 1970-01-01
    • 1970-01-01
    • 2012-02-29
    • 2020-05-12
    • 2010-09-23
    • 2021-12-18
    • 1970-01-01
    相关资源
    最近更新 更多