final HttpResponse response = this.call(queryUri);
entity = response.getEntity();public HttpResponse call(final URI queryUri) throws Exception
{
Future<HttpResponse> futureResponses = executor.submit(new Callable<HttpResponse>()
{
@Override
public HttpResponse call() throws Exception
{
final HttpGet httpget = new HttpGet(queryUri);
return httpclient.execute(httpget);
}
});
return futureResponses.get(A9_CALL_TIMEOUT, TimeUnit.MILLISECONDS);
}
final HttpResponse response = this.call(queryUri);
entity = response.getEntity();
parse(entity.getcontent());
想知道如何模拟所有对象,有人能为我提供测试类的可行代码吗?
答案 0 :(得分:1)
我建议您将Callable
的创建提取到受保护的方法。
public Callable<HttpResponse> createCallable(String queryUri){
return new Callable<HttpResponse>(){
@Override
public HttpResponse call() throws Exception
{
final HttpGet httpget = new HttpGet(queryUri);
return httpclient.execute(httpget);
}
});
}
我认为你真的不需要EasyMock进行这项测试。事实上,没有它可能会更容易。在测试中,您可以覆盖此方法以返回测试存根。我认为如果get
超时,那么它将抛出一个TimeoutException并且实际上不会取消该作业。所以我认为你只需要捕获TimeoutException以确保一切正常。
所以也许你的模拟器只需要睡眠A9_CALL_TIMEOUT
加上一些额外的软糖因子。
@Test
public void testTimeout(){
Subclass sut = new Subclass(){
@Override
public Callable<HttpResponse> createCallable(String queryUri){
return new Callable<HttpResponse>(){
@Override
public HttpResponse call() throws Exception{
try{
Thread.sleep(A9_CALL_TIMEOUT *2);
catch(InterruptException e) {}
}
});
};
//you can also use Junit ExpectedException rule instead
// of the try catch here
try{
sut.runQueryMethodWithExecutor();
fail("should throw timeout");
}catch(TimeoutException e){
//expected
}
}