[Fixed]-How to handle view throwing manual exception in django in unit-testing?

1👍

This should work:

resp = self.client.get(url)
self.assertEqual(resp.status_code, 404)

Run your tests via:

python manage.py test

If it does not, recheck your code and supply an error message.

👤Udi

0👍

If self.assertEqual doesn’t work you could try it with a with tag as shown here
assertRaises(exception, callable, *args, **kwds)

with self.assertRaises(Http404):
    // your logic here

For example. I have a function that will return an order or raise a HTTP 404 response

from django.http import Http404

def test_get_order_with_method_404(self):
    client = MyPaymentClient("super_secret_key")
    with self.assertRaises(Http404):
        client.get_order_with_method("payment_id", "payment_method")

You could also do it with get_object_or_404

Example:

from django.http import Http404
from django.shortcuts import get_object_or_404

with self.assertRaises(Http404):
    get_object_or_404(MyModel, some_argument="MyCriteria")

Well i guess you get the point. Hope this helps you out!

Leave a comment