Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

170
Views
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 answers
Answer question

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!