如何测试Django的ClassBasedView中的get_success_url?

问题描述 投票:0回答:1

我想测试我的success_url方法,但找不到正确测试的方法,也无法增加我的代码覆盖率。

#views.py

def get_success_url(self):
    if self.question.type in [
        Question.MULTIPLE_TYPE,
        Question.SINGLE_TYPE
    ]:
        return reverse("question")
    else:
        return reverse("question_answers", kwargs={"id": self.question.pk, "type": Answer.MULTIPLE})

这是我在我的test.py文件中试过的。

#tests.py
from factories import QuestionFactory

def test_get_success_url(self):
    self.client.force_login(user=self.user)
    question = QuestionFactory(owner=self.user)
    if question.type in [
        Question.MULTIPLE_TYPE,
        Question.SINGLE_TYPE
    ]:
        response = self.client.get(reverse("question"))
    else:
        response = self.client.get(
            reverse("question_answers", kwargs={"id": self.question.pk, "type": Answer.MULTIPLE})
        )
    self.assertEqual(response.status_code, 200)
django django-views django-class-based-views django-testing django-tests
1个回答
1
投票

如果你想测试CBV中的get_success_url()方法,你需要调用CBV本身。所以举个例子。

# views.py
class SuccessTestingView(FormView):
    def get_success_url():
        # Your that you want to test here.

测试

# tests.py
from factories import QuestionFactory

    class SuccessfullRedirect(TestCase):

        def test_successfull_redirect_1(self):
            self.client.force_login(user=self.user)
            response = self.client.post(path_to_cbv, criteria_that_leads_to_first_result)
            self.assertRedirects(response, reverse("question"))

        def test_succesfull_redirect_2(self):
            self.client.force_login(user=self.user)
            response = self.client.post(path_to_cbv, criteria_that_leads_to_second_result)
            self.assertRedirects(response, reverse("question_answers", kwargs={"id": self.question.pk, "type": Answer.MULTIPLE}))

你需要测试的是视图本身,而不是调用成功网址的结果。希望能帮到你。

© www.soinside.com 2019 - 2024. All rights reserved.