我對自動化測試相當陌生,我一直在用mockito嘲笑一個類時遇到了一些麻煩。基本上我試圖做的是利用正在發送到方法的接口,當調用此方法(Request(Response))時,我希望mockito介入並從接口中傳遞一個方法作爲參數傳遞一個對象(callback.OnSuccess(的OBJ))。這裏是我的意思,我就開始了我的生產代碼的例子,我已經採取了原位缺口所需的一切:Mokito,嘲笑方法行爲
ServerRequest類
public void Request(ResponseInterface callback){
//The contents of this class isnt really important as I do not wish to use any of it
//but in general this makes a request to the server and if the request is a success then
Object obj = ProcessResponse(Response);
callback.OnSuccess(obj);
//otherwise
Object obj = ProcessResponse(Response);
callback.OnError(obj);
}
ResponseInterface
public interface ResponseInterface(){
void OnSuccess(Object resp);
void OnError(Object resp);
}
MainActivity
public void MakeRequest(){
ServerRequest.Request(new ResponseInterface(){
@Override
public void OnSuccess(Object objResponse){
//do something to show user the request was successful depending on the current activity
}
@Override
public void OnError(String e){
//do something depending on the current activity
})
}
到目前爲止,我已經嘗試了多種方法,最好的我coul d提出的是在下面的代碼中,但是我相信你可以從帖子中看出它不起作用,但我會把它留在這裏,因爲它可能會讓某人更好地瞭解我正在嘗試做什麼。
ServerRequest mockReq = mock(ServerRequest.class);
Mockito.doAnswer(new Answer<Void>() {
@Override
public Void answer(InvocationOnMock invocation) throws Throwable {
System.out.println("Running first time");
Object[] arguments = invocation.getArguments();
ResponseInterface inter = (ResponseInterface) arguments[2];
Object obj = "Already taken";
inter.OnSuccess(obj);
return null;
}
}).when(mockReq).InformationRequest(ArgumentMatchers.anyMap(),anyString(),ArgumentMatchers.<ServerInterface>any());
任何有關此事的幫助將不勝感激,因爲我不知道我在做什麼。
什麼是'RequestDataInterface'。請編輯以發佈1 /您要測試的代碼2 /測試代碼(您擁有的代碼)並刪除無關的所有內容。 – 2017-07-16 17:09:02
對不起,我正在搞模擬早點忘了恢復,我想我現在已經解決了所有問題。 –