简体   繁体   English

如何在 Mockito 参数捕获器中多次捕获相同的 object

[英]How to capture same object multiple times in Mockito argument captor

I was writing a Junit to test a scenario where an object changes its variables and saves it into the database 2 times.我正在编写 Junit 来测试 object 更改其变量并将其保存到数据库中 2 次的场景。 The argumentCaptor is invoked in save operation. argumentCaptor在保存操作中被调用。 The getAllValues() is returning two records. getAllValues()返回两条记录。 But both values are referenced to the same last capture record.但是这两个值都引用了相同的最后一个捕获记录。

ImplimentationClass.java ImplimentationClass.java

 ...

myObj.setVariable(oneValue);
saveMyObj(myObj);
myObj.setVariable(otherValue);
saveMyObj(myObj);

...

saveMyObj(MyObject myObj){
repository.save(myObj);
}

ImplimentationClassTest.java ImplimentationClassTest.java


private ImplimentationClass underTest ;

@Mock
private Repository mockRepository;

@Before
public void setup(){
  initMocks(this);
  underTest = new ImplimentationClassTest();
}

@Test
public void test(){
ArgumentCaptor<MyObject> captor = ArgumentCaptor.forClass(MyObject.class);
MyObject obj = new MyObject(value);
underTest.implementedMethod(obj);
verify(mockRepository, times(2)).save(captor.capture());
assertEquals(oneValue, captor.getAllValues().get(0).getVariable()); //failing here -getting otherValue
assertEquals(otherValue, captor.getAllValues().get(1).getVariable());

}

Any idea how to capture same object multiple times?知道如何多次捕获相同的 object 吗?

The problem from your test originates from this piece of code.您测试的问题源于这段代码。

myObj.setVariable(oneValue);
saveMyObj(myObj);
myObj.setVariable(otherValue);
saveMyObj(myObj);

Once you change the variable inside of myObj you change it for all references.一旦您更改了myObj中的variable ,您就可以为所有引用更改它。 Note that the ArgumentCaptor does not make a deep copy of myObj .请注意, ArgumentCaptor不会制作myObj的深层副本。 So you will end up with two references to myObj , which only has the latest state.所以你最终会得到两个对myObj的引用,它只有最新的 state。

To avoid this you might want to pass a different instance to the second call.为避免这种情况,您可能希望将不同的实例传递给第二次调用。


Another alternative might be to use doAnswer instead and check the correctness of the paramter inside that method.另一种选择可能是改用doAnswer并检查该方法中参数的正确性。

Check this answer for an example.检查此答案以获取示例。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM