<p>使用<code>AsyncHTTPTestCase</code>模式的主要原因是,它为您生成了所有的请求内容。当然,也可以使用<code>AsyncTestCase</code>并手动处理它。</p>
<p>AsyncTestCase示例。因为它将测试协同程序的<code>get</code>方法,所以我们将使用<a href="http://www.tornadoweb.org/en/stable/testing.html#tornado.testing.gen_test" rel="nofollow noreferrer">^{<cd4>}</a>使其更简单一些。<a href="http://www.tornadoweb.org/en/stable/web.html#tornado.web.RequestHandler" rel="nofollow noreferrer">^{<cd5>}</a>需要<code>Application</code>和<code>HTTPRequest</code>对象。因为我们没有转发应用程序的设置、ui_方法等,<code>Application</code>是一个简单的模拟。</p>
<pre><code>from tornado.testing import AsyncTestCase, gen_test
from tornado.web import Application
from tornado.httpserver import HTTPRequest
from unittest.mock import Mock
class TestSomeHandler(AsyncTestCase):
@gen_test
def test_no_from_date_param(self):
mock_application = Mock(spec=Application)
payload_request = HTTPRequest(
method='GET', uri='/test', headers=None, body=None
)
handler = SomeHandler(mock_applciation, payload_request)
with self.assertRaises(ValueError):
yield handler.get()
</code></pre>
<p>我看你该用哪种模式。我为http动词方法(get、post等)选择<code>AsyncHTTPTestCase</code>,因为:</p>
<ul>
<li>这样比较容易</li>
<li>此方法的使用者是HTTP客户端,因此断言响应代码body非常有意义</li>
<li>它防止了过于复杂的方法</li>
</ul>
<p>当然,处理程序的其他方法都是用<code>AsyncTestCase</code>测试的。</p>