使用 Mockito 验证方法后没有调用任何内容

Use Mockito to verify that nothing is called after a method(使用 Mockito 验证方法后没有调用任何内容)
本文介绍了使用 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 验证方法后没有调用任何内容的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

本站部分内容来源互联网,如果有图片或者内容侵犯了您的权益,请联系我们,我们会在确认后第一时间进行删除!

相关文档推荐

How to send data to COM PORT using JAVA?(如何使用 JAVA 向 COM PORT 发送数据?)
How to make a report page direction to change to quot;rtlquot;?(如何使报表页面方向更改为“rtl?)
Use cyrillic .properties file in eclipse project(在 Eclipse 项目中使用西里尔文 .properties 文件)
Is there any way to detect an RTL language in Java?(有没有办法在 Java 中检测 RTL 语言?)
How to load resource bundle messages from DB in Java?(如何在 Java 中从 DB 加载资源包消息?)
How do I change the default locale settings in Java to make them consistent?(如何更改 Java 中的默认语言环境设置以使其保持一致?)