我有一个网站,其中所有 View 都将使用@login_required 进行保护,当然,登录 View 除外。
但是,如果我不向请求添加经过身份验证的用户,使用装饰器将导致调用这些 View 的测试失败。我知道这可以在 setUp() 中完成,但在任何测试类中编写同一行都不符合 DRY 原则。
还有比这更好的方法吗?
最佳答案
正如您所说,您可以将登录移动到 setUp
方法,以避免在测试类中的每个测试中重复。
如果您不喜欢在每个测试类中复制 setUp
方法,您可以创建自己的测试用例类或 mixin。
class LoggedInTestCase(TestCase):
def setUp(self):
user = User.objects.create_user(username='username', password='password')
self.client.login(username='username', password='password')
class MyTestCase(LoggedInTestCase):
def test_stuff(self):
...
如果您在子类中覆盖了 setUp
方法,请记住调用 super()
。
class MyOtherTestCase(LoggedInTestCase):
def setUp(self):
super(MyOtherTestCase, self).setUp()
# other setUp code goes here
def test_other_stuff(self):
...
关于django 使用 login_required 装饰器测试 DRY View ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36403788/