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

时间:2016-09-21 12:27:38

标签: java android unit-testing mockito powermockito

我的Android应用程序上有以下代码:

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

我想测试的是,使用Mockito是将MyObject的相同实例传递给MyApiRequest构造函数。让我们说我们不知道MyApiRequest的外观。我只想测试那里&#34; myObject&#34; execute()方法的param与MyApiRequest recieves相同。

1 个答案:

答案 0 :(得分:0)

是的,您可以使用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());