使用Mockito验证方法后没有调用任何内容 [英] Use Mockito to verify that nothing is called after a method

查看:595
本文介绍了使用Mockito验证方法后没有调用任何内容的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用Mockito在Java中编写单元测试,我想验证某个方法是在对象上调用的最后一个

I'm using Mockito to write a unit test in Java, and I'd like to verify that a certain method is the last one called on an object.

我在测试代码中做了类似的事情:

I'm doing something like this in the code under test:

row.setSomething(value);
row.setSomethingElse(anotherValue);
row.editABunchMoreStuff();
row.saveToDatabase();

在我的模拟中,我不关心我编辑行中所有内容的顺序,但是在我保存之后尝试对它做更多的事情是非常重要的。有没有一个很好的方法来做到这一点?

In my mock, I don't care about the order in which I edit everything on the row, but it's very important that I not try to do anything more to it after I've saved it. Is there a good way to do this?

请注意,我不是在寻找verifyNoMoreInteractions:它不会确认saveToDatabase是最后调用的东西,如果我在行上调用任何内容,它也会失败我没有明确核实。我希望能够这样说:

Note that I'm not looking for verifyNoMoreInteractions: it doesn't confirm that saveToDatabase is the last thing called, and it also fails if I call anything on the row that I don't explicitly verify. I'd like to be able to say something like:

verify(row).setSomething(value);
verify(row).setSomethingElse(anotherValue);
verifyTheLastThingCalledOn(row).saveToDatabase();

如果有帮助,我会从执行此操作的JMock测试切换到Mockito:

If it helps, I'm switching to Mockito from a JMock test that did this:

row.expects(once()).method("saveToDatabase").id("save");
row.expects(never()).method(ANYTHING).after("save");


推荐答案

我认为这需要更多的自定义工作。

I think it requires more custom work.

verify(row, new LastCall()).saveToDatabase();

然后

public class LastCall implements VerificationMode {
    public void verify(VerificationData data) {
        List<Invocation> invocations = data.getAllInvocations();
        InvocationMatcher matcher = data.getWanted();
        Invocation invocation = invocations.get(invocations.size() - 1);
        if (!matcher.matches(invocation)) throw new MockitoException("...");
    }
}

上一个答案:

你是对的。 verifyNoMoreInteractions是你需要的。

You are right. verifyNoMoreInteractions is what you need.

verify(row).setSomething(value);
verify(row).setSomethingElse(anotherValue);
verify(row).editABunchMoreStuff();
verify(row).saveToDatabase();
verifyNoMoreInteractions(row);

这篇关于使用Mockito验证方法后没有调用任何内容的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆