如何将TDD应用于基于Django类的通用视图? [英] How TDD can be applied to Django Class based Generic Views?

查看:143
本文介绍了如何将TDD应用于基于Django类的通用视图?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

由于Django中基于类的通用视图涉及框架中的一些工作,我发现很难在TDD风格中使用它们。现在我使用TestClient从http嘲笑的堆栈访问视图,但是我希望在使用TestClient进行功能测试之前,正确地对特定的方法进行单元测试(es。覆盖get_object和get_queryset)。



有没有(快速)的方法来获取一个适当的ClassView实例来执行单元测试?

解决方案

通常,这将包括通过 RequestFactory ,并使用关键字参数实例化视图类。然后,您可以调用任何视图方法并评估结果,传递任何所需的参数。



我建议您查看基础 查看 类,具体来说 __ init __ as_view dispatch 方法。它们对于了解框架与视图对象的交互至关重要。



注意到最重要的一点是,在请求 - 响应过程中期望调用视图方法,所以他们被允许依靠 self.request self.args self .kwargs 在被呼叫之前存在,所以请确保已经覆盖了。


Since Class based Generic Views in Django involve some work by the framework I find very hard to work with them in a TDD style. Now I use the TestClient to access the view from the http mocked stack, but I would prefer to properly unittest specific methods (es. overrides of get_object and get_queryset ) before 'functional' testing with the TestClient.

Is there a ( quick ) way to obtain a proper instance of a ClassView to perform unit test on it?

解决方案

Generally, that would include creating a request via the RequestFactory and instantiating the view class with keyword arguments. Afterwards, you can call any of the view methods and evaluate the result, passing any required arguments.

I'd recommend that you review the base View class, specifically the __init__, as_view and dispatch methods. They're crucial to understanding how the framework interacts with view objects.

The most important bit to notice there is that view methods expect to be called during a request-response process, so they're allowed to rely upon self.request, self.args and self.kwargs to be present before they're called, so make sure you've got that covered.

这篇关于如何将TDD应用于基于Django类的通用视图?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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