你可以使用一個ArgumentCaptor
來獲取傳遞到dao.method2(...)
值,然後使上斷言。
例如,說我有這個DAO ...
public interface DAO {
Response method1(Request request);
Response method2(Request request);
}
而這個服務...
public class Service {
private DAO dao;
public void setDao(DAO dao) {
this.dao = dao;
}
public Response serviceMethod(Request someArgs) {
Response response1 = dao.method1(someArgs);
String someItem = response1.getTheResponse();
Request request2 = new Request(someItem);
return dao.method2(request2);
}
}
,此服務的測試可能是......
import static org.fest.assertions.Assertions.assertThat;
import static org.mockito.Matchers.any;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import org.junit.Before;
import org.junit.Test;
import org.mockito.ArgumentCaptor;
import org.mockito.Captor;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
public class ServiceTest {
@Mock
private Request request;
@Mock
private Response response;
@Mock
private Response serviceResponse;
@Mock
private DAO dao;
@InjectMocks
private Service service;
@Captor
private ArgumentCaptor<Request> requestCaptor;
@Before
public void setup() {
MockitoAnnotations.initMocks(this);
}
@Test
public void shouldDoServiceMethod() {
// Set up
when(dao.method1(request)).thenReturn(response);
when(response.getTheResponse()).thenReturn("[ARGUMENT]");
when(dao.method2(any(Request.class))).thenReturn(serviceResponse);
// Code under test
Response actualResponse = service.serviceMethod(request);
// Verification
assertThat(actualResponse).isSameAs(serviceResponse);
verify(dao).method2(requestCaptor.capture());
Request actualSecondRequest = requestCaptor.getValue();
assertThat(actualSecondRequest.getArgs()).isEqualTo("[ARGUMENT]");
}
}
重點行...
verify(dao).method2(requestCaptor.capture());
這驗證了method2
被調用並捕獲了它被調用的值。
那麼你得到的價值...
Request actualSecondRequest = requestCaptor.getValue();
...然後你可以驗證相關的信息被設置...
assertThat(actualSecondRequest.getArgs()).isEqualTo("[ARGUMENT]");
希望這有助於。
爲了完整起見,這裏的Request
和Response
...
public class Request {
private String args;
public Request(String args) {
this.args = args;
}
public String getArgs() {
return args;
}
}
public class Response {
private String theResponse;
public Response(String theResponse) {
this.theResponse = theResponse;
}
public String getTheResponse() {
return theResponse;
}
}
這是一個真正的Java代碼,或只是一個僞代碼?我看到mockResponse1是一個實際的實例,mockResponse2也是一個實際的實例。如果你打電話給這些嘲笑,我期待像模擬(Response1.class)和模擬(Response2.class)。如果你真的沒有注意到這一點,那麼你的問題。 –
''代碼是''可能會讓你難以發現問題,當你不包含實際的模擬創建代碼(= dao'),並且還包括代碼將模擬注入到服務類中的代碼。此外'mockRequest2'沒有在你的測試代碼中的任何地方定義 –
這是僞代碼 –