Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

171
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda