使用 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 验证方法后没有调用任何内容的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

Show progress during FTP file upload in a java applet(在 Java 小程序中显示 FTP 文件上传期间的进度)
How to copy a file on the FTP server to a directory on the same server in Java?(java - 如何将FTP服务器上的文件复制到Java中同一服务器上的目录?)
FTP zip upload is corrupted sometimes(FTP zip 上传有时会损坏)
Enable logging in Apache Commons Net for FTP protocol(在 Apache Commons Net 中为 FTP 协议启用日志记录)
Checking file existence on FTP server(检查 FTP 服务器上的文件是否存在)
FtpClient storeFile always return False(FtpClient storeFile 总是返回 False)