我对自动化测试相当陌生,我一直在用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
对不起,我正在搞模拟早点忘了恢复,我想我现在已经解决了所有问题。 –