Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

172
Visualizações
Mocking forms in view unit tests

I can't seem to be able to mock the behaviour of a form when unit testing views.

My form is a simple ModelForm and resides in profiles.forms. The view is (again) a simple view that checks whether the form is valid and then redirects.

views.py

from django.http import HttpResponseRedirect
from django.shortcuts import render
from django.urls import reverse
from profiles.forms import ProfileForm

def home(request):
    form = ProfileForm()

    if request.method == 'POST':
        form = ProfileForm(request.POST)

        if form.is_valid():
            profile = form.save()
            return HttpResponseRedirect(reverse("thanks"))

My test looks like this:

class TestViewHomePost(TestCase):
    def setUp(self):
        self.factory = RequestFactory()

    def test_form(self):
        with mock.patch('profiles.views.ProfileForm') as mock_profile_form:
            mock_profile_form.is_valid.return_value = True
            request = self.factory.post(reverse("home"), data={})
            response = home(request)
            logger.debug(mock_profile_form.is_valid.call_count)    # "0"

is_valid is not being called on the mock, which means ProfileForm is not patched.

Where did I make a mistake?

over 4 years ago · Santiago Trujillo
1 Respostas
Responde à pergunta

0

I was able to fix mocking is_valid as following:

def test_form(self):
        with mock.patch('profiles.views.ProfileForm.is_valid') as mock_profile_form:
            mock_profile_form.return_value = True
            request = self.factory.post(reverse("home"), data={})
            response = home(request)

note: and you could use mock_profile_form.assert_called_once() to check if the mock has been called.

over 4 years ago · Santiago Trujillo Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda