简体   繁体   English

如何检查作为参数传递给使用 Mockito 模拟的服务的 object 的属性

[英]How do I check attributes of an object passed as parameter to a service mocked with Mockito

I am new to Mockito and I am not able to test this scenario:我是 Mockito 的新手,我无法测试这种情况:

I want to test a ws controller that takes a json string, parses it and calls a method from a service with the resulted object.我想测试一个 ws controller ,它接受一个 json 字符串,解析它并从服务中调用一个方法,结果是 object。 I have decided to mock the service dependency with Mockito and I am trying to verify that the correct method from this mock is called with the correct parameter.我决定使用 Mockito 来模拟服务依赖关系,并且我正在尝试验证是否使用正确的参数调用了该模拟中的正确方法。

I think the problem is that the verify method compares the references of the two objects.我认为问题在于 verify 方法比较了两个对象的引用。 Is there a way to compare certain attributes of the object passed as parameter?有没有办法比较作为参数传递的 object 的某些属性? Is there a solution other than overriding the equals method of the "DummyObj" from the example?除了覆盖示例中“DummyObj”的equals方法之外,还有其他解决方案吗?

*short recap: the controller.recive( json ) method takes a string and calls service.onMessage( resultedObj ) with the parsed obj as param. *简短回顾: controller.recive( json ) 方法接受一个字符串并调用 service.onMessage(ResultObj ) 并将解析的 obj 作为参数。 the onMessage method is not returning anything. onMessage 方法没有返回任何内容。 * *

The test looks like this:测试看起来像这样:

@Test
public void test() {
    DummyObj dummyObj = new DummyObj();
    String dummyObjJson = new Gson().toJson(dummyObj);

    controller.recive(dummyObjJson);

    verify(mockedService).onMessage(dummyObj);
}

One way is using ArgumentMatchers.argThat一种方法是使用ArgumentMatchers.argThat

verify(mockedService)
  .onMessage(ArgumentMatchers.argThat(obj->obj.getName().equals(dummyObj.getName())));

And the another way is using ArgumentCaptor另一种方法是使用ArgumentCaptor

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

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

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