单元测试网络响应.在调试时起作用,而不是在实际运行时起作用 [英] Unit testing a network response. Works when debugging, not when actually running

查看:111
本文介绍了单元测试网络响应.在调试时起作用,而不是在实际运行时起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前正在尝试测试是否实际收到了网络响应.

I am currently attempting to test that a network response is actually being received.

虽然我知道这不是我应该做的测试,但出于我自己的好奇心,我想尽可能地继续下去.

While I understand that this isn't what I should be doing with regards to testing, its a curiosity of my own volition and I'd like to carry on if possible.

就目前而言,我已经成功创建了测试.请求被发送到齐射队列而没有问题.

As it stands, I have successfully created the test. A request is sent to a volley queue without issue.

现在奇怪的部分:

该请求从不执行.这是我如何测试的想法:

That request is never executed. Here's an idea of how I'm testing it:

 @Test
    public void testSimpleGetResponseFromServerVolley() throws Exception {
        final CountDownLatch signal = new CountDownLatch(1);

        NetworkClass.NetworkListener listener = new NetworkClass.NetworkListener() {
            @Override
            public void onResponse(Response response) {
                assertThat(response != null);
                System.out.println("Got Response");
                signal.countDown();

            }

            @Override
            public void onError(Throwable error) {
                System.out.println("No Response");
                signal.countDown();
            }
        };
        NetworkClass.getResponseFromServer(null, listener);
        signal.await();
    }

此代码意外导致测试挂起,并且永远无法完成.

This code unexpectedly causes the test to hang and never complete.

但是,这是我不再失去对情况的理解的地方:

如果我通过 debug 运行测试并逐步进行测试,则测试将成功执行并收到响应.

If I run the test via debug and step through line by line, the test successfully executes, and response is received.

我正在发生的事情:

当我通过调试逐步完成时,齐射requestQueue成功进行并发出请求,并且在调用await()之前已收到响应.

When I step through via debug, the volley requestQueue successfully carries on and makes the request, and the response is received before await() is called.

当我不通过调试逐步执行操作时,await()会阻塞处理所有这些操作的线程.

When I don't step through via debug, await() is blocking the thread which handles all of that.

关于如何处理此问题的任何想法?

Any ideas on how I can handle this?

推荐答案

Volley依靠Looper.getMainLooper()来处理其执行.使用RobolectricTestRunner时,Robolectric会对此进行模拟,因此将无法正确设置它,从而导致测试失败.

Volley relies on Looper.getMainLooper() to handle its executions. When using a RobolectricTestRunner, Robolectric mocks this out and as such it will not be correctly set up, thus resulting in a failed test.

在我的特定情况下,当我使用断点时,系统实际上确实设置了主循环程序,因为系统正在利用它来显示断点/调试工具.因此,这描述了在我最初的问题中发现的行为背后的原因.

In my specific case, when I was using breakpoints, the system actually does set up the main looper, because the system is utilizing it to show the breakpoints / debugging tools. This thus describes the reasoning behind the behaviour found in my initial question.

现在要获得在单元测试期间通过Volley获得真实网络响应的解决方案,必须将执行程序更改为不使用主循环程序.

Now for a solution as to getting real network responses with Volley during a unit test, the executor must be changed to not be using the main looper.

作为一个简单的解决方案,创建一个依赖于Executor.singleThreadExecutor()而不是Main Looper的请求队列.

As an easy solution, create a request queue that relies on Executor.singleThreadExecutor() instead of the Main Looper.

这是我的意思:

    //Specific test queue that uses a singleThreadExecutor instead of the mainLooper for testing purposes.
public RequestQueue newVolleyRequestQueueForTest(final Context context) {
    File cacheDir = new File(context.getCacheDir(), "cache/volley");
    Network network = new BasicNetwork(new HurlStack());
    ResponseDelivery responseDelivery = new ExecutorDelivery(Executors.newSingleThreadExecutor());
    RequestQueue queue = new RequestQueue(new DiskBasedCache(cacheDir), network, 4, responseDelivery);
    queue.start();
    return queue;
}

然后,将其用作测试期间Volley的请求队列.

Then, use that as your request queue for Volley during the tests.

这里的关键是:

ResponseDelivery responseDelivery =新的ExecutorDelivery(Executors.newSingleThreadExecutor());

希望这会有所帮助!

这篇关于单元测试网络响应.在调试时起作用,而不是在实际运行时起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆