<p>您可以使用模拟库(unittest.mock在python3.5中):</p>
<pre><code>import unittest
from cStringIO import StringIO
from mock import patch
import tornado.web
import tornado.httpclient
from tornado.testing import AsyncHTTPTestCase
class TestHandler(tornado.web.RequestHandler):
@tornado.web.asynchronous
def get(self):
def request_cb(response):
self.finish(response.body)
http_client = tornado.httpclient.AsyncHTTPClient()
request = tornado.httpclient.HTTPRequest('http://example.com')
http_client.fetch(request, request_cb)
class TestHttpService(AsyncHTTPTestCase):
def setUp(self):
super(TestHttpService, self).setUp()
self.async_client = tornado.httpclient.AsyncHTTPClient(self.io_loop)
self.async_patcher = patch('tornado.httpclient.AsyncHTTPClient')
self.mocked_async_client = self.async_patcher.start()
def get_app(self):
return application
def test_async_httpclient(self):
request = tornado.httpclient.HTTPRequest('http://example.com')
response = tornado.httpclient.HTTPResponse(request, 200,
buffer=StringIO('test'))
self.mocked_async_client().fetch.side_effect = lambda x,y: y(response)
self.async_client.fetch(self.get_url('/'), self.stop)
resp = self.wait()
self.assertEquals(resp.body, 'test')
application = tornado.web.Application([(r'/', TestHandler)])
</code></pre>