使用 mockito 验证对象属性值

Verify object attribute value with mockito(使用 mockito 验证对象属性值)
本文介绍了使用 mockito 验证对象属性值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着跟版网的小编来一起学习吧!

问题描述

我有一个方法调用,我想用 mockito 模拟.首先,我创建并注入了一个对象实例,将在该实例上调用该方法.我的目标是验证方法调用中的对象之一.

I have a method call which I want to mock with mockito. To start with I have created and injected an instance of an object on which the method will be called. My aim is to verify one of the object in method call.

mockito 是否允许您在调用 mock 方法时断言或验证对象及其属性?

Is there a way that mockito allows you to assert or verify the object and it's attributes when the mock method is called?

例子

Mockito.verify(mockedObject)
       .someMethodOnMockedObject(
              Mockito.<SomeObjectAsArgument>anyObject())

我不想做 anyObject() 我想检查参数对象是否包含一些特定字段

Instead of doing anyObject() i want to check that argument object contains some particular fields

Mockito.verify(mockedObject)
       .someMethodOnMockedObject(
              Mockito.<SomeObjectAsArgument>**compareWithThisObject()**)

推荐答案

添加到 Mockito 的新功能使这变得更加容易,

New feature added to Mockito makes this even easier,

ArgumentCaptor<Person> argument = ArgumentCaptor.forClass(Person.class);
verify(mock).doSomething(argument.capture());
assertEquals("John", argument.getValue().getName());

查看 Mockito 文档

Take a look at Mockito documentation

如果有多个参数,并且只需要捕获单个参数,请使用其他 ArgumentMatchers 包装其余参数:

In case when there are more than one parameters, and capturing of only single param is desired, use other ArgumentMatchers to wrap the rest of the arguments:

verify(mock).doSomething(eq(someValue), eq(someOtherValue), argument.capture());
assertEquals("John", argument.getValue().getName());

这篇关于使用 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)