简体   繁体   English

单元测试:如何验证参数是否传递给构造函数?

[英]Unit testing: how to verify that an argument was passed to a constructor?

I have the following code on my Android application: 我的Android应用程序上有以下代码:

public Observable<Person> execute(MyObject myObject) {
    return service.execute(new MyApiRequest(myObject));
}

What I want to test, using Mockito is that the same instance of MyObject is passed to MyApiRequest constructor. 我想测试的是,使用Mockito是将MyObject的相同实例传递给MyApiRequest构造函数。 Let's say we don't know how MyApiRequest looks. 假设我们不知道MyApiRequest的外观。 I only want to test that there "myObject" param from execute() method is the same as MyApiRequest recieves. 我只想测试execute()方法中的“myObject”参数是否与MyApiRequest接收相同。

Yes, you can use an ArgumentCaptor to inspect the MyApiRequest that comes back. 是的,您可以使用ArgumentCaptor检查返回的MyApiRequest。

// Create the object and the captor.
ArgumentCaptor<MyApiRequest> myApiRequestCaptor =
    ArgumentCaptor.forClass(MyApiRequest.class);
MyObject myObject = new MyObject();

// Run the test.
systemUnderTest.execute(myObject);

// Capture the MyApiRequest.
verify(service).execute(myApiRequestCaptor.capture());
MyApiRequest myApiRequest = myApiRequestCaptor.getValue();

// Now check the object identity.
assertSame("MyApiRequest should have the exact same passed-in object.",
    myObject, myApiRequest.getParameter());

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

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