java - 如果该参数的状态已更改,如何验证传递的参数是否具有正确的参数?

标签 java unit-testing mockito

我正在尝试使用

验证对象
@Captor
ArgumentCaptor<User> userArgumentCaptor
...//define user with name and jailName - var = user1
...//Call the method under test.
verify(userDao).getName(userArgumentCaptor.capture());
verify(userDai).getJailName(userArgumentCaptor.capture());
assertThat(userArgumentCaptor.getAllValues()).isEqualTo(Arrays.asList(user1user1));
/**
* Notice here that I had to use same object to verify even when I captured it in two different situations.
*/

对于场景,

User user = new User(); //Object under inspection.
user.setId(); //Changing state here.
userDao.getName(user); //Capture user here.
...
if(someBooleanCondition) {
    user.setJailStatus(true); //Changing state here.
    userDao.getJailName(user); //Capture user here.
}

在断言 userArgumentCaptor.getValue() 时,它正在检查更新后的值。这实际上是有道理的,因为我捕获的是对象而不是对象的状态。

但是,如何验证对象在传递时的状态?

最佳答案

我认为这是不可能的。即使在查看最新版本的 ArgumentCaptor 时也是如此(此时模拟 2.7.21);根本没有迹象表明要朝那个方向发展。

ArgumentCaptor 提供的服务的目的分别是收集调用方法时使用的那些参数。

基本上,您要问的是:有没有办法在调用发生时进行额外检查。

我想,这可能成为可能:框架必须允许您注册一个回调,只要在模拟对象上调用特定方法,就会调用该回调。但这在今天是不可能的。

我看到的唯一解决方案 - 而不是做

@Mock
YourRealDaoClass theMockedDao

你必须做

class MockedDaoClass extends YourRealDaoClass {

然后自己实现这些事情。这样你就可以把:

YourRealDaoClass theMockedDao = new MockedDaoClass(...

进入你的测试。与其他一些逻辑一起启用您需要的东西。

换句话说:Mockito 生成的模拟不允许您在模拟对象上调用方法时进行增强测试。如果您需要它(例如进行如下测试:param.getFoo().equals()),那么您将返回创建自己的 stub /模拟类。

你必须做的:

  • 仔细查看Dao类所有的方法
  • 决定您需要覆盖哪一个,以确保它们返回您需要的值,使模拟与您的生产代码一起工作
  • 对于接收您感兴趣的那些参数的方法:要么在那里进行检查;要么或收集值以供以后检查

关于java - 如果该参数的状态已更改,如何验证传递的参数是否具有正确的参数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43274045/

相关文章:

java - Telegram bot webhooks、Tomcat 上的 servlet 和 openshift cloud

java.lang.NullPointerException...崩溃报告

c++ - 谷歌模拟 : Is it ok to use global mock objects?

java - Spring MVC : Unit testing a controller with MockMultipartFIle and other form data

Kotlin + Mockito : getting a null

java - 在单元测试中模拟注入(inject)字段

java - 使用 Mockito 模拟接口(interface)

java - Canvas 作为 ImageView/位图

java - Iterator.next() 上的 ConcurrentModificationException

python - 为什么 flask 测试会产生两个测试实例?