How to Test Abstract Models

G’day Folks,

I wonder if there is an official or best practice guide on testing abstract models. I have read and tried lots of solutions, which are all very old, and have dug into the code, but I’m missing something because I have not been able to do this successfully.

My abstract class does quite a bit, I would like to make sure it continues to work, and I prefer not to test every child class for those functions if possible.

To ensure that the testing errors are not something I have introduced with settings and configuration, I have started with a new Django project with one App and one Abstract model containing one field.

I have read this ticket, but I’m not sure it answers my question.

I’m using Django 4.0.5.

Thank you

I’m not one much for writing tests, but I’m curious - what leads you to the conclusion you would need to test every child class for those functions?

If those functions in the parent class don’t depend upon any behavior of the child class, why wouldn’t you be satisfied with testing just one child class for those functions? (And if the behavior of the parent class does depend upon functions defined in the child class, then wouldn’t you be testing those child class functions?)


That’s a way I’ve been doing it.

Also, this doesn’t strictly answer the question, but consider why you’re testing those particular functions. There’s more than one purpose to testing, but I once read one worded in a way that made beautifully sense: you’re testing to see if your software respects the contract it has with the client/user.

In that sense, your client won’t be using the abstract model A, but rather its concrete children B and C. Considering that, it might be worth going, “okay let’s make sure the methods on those two classes do what a client would expect them to” and testing the children directly.

This will also aid you if one day you decide C is to override the inherited method and change some of its internal logic. It’d be much harder to find any bugs or regression introduced if you were somehow only testing the abstract parent, whereas by testing the children separately you’d immediately know because the tests for C would be failing.

1 Like

@KenWhitesell your question did make me think about this, and I think I just broke my brain trying to figure out how to test the abstract models.

Using one child class makes sense.

Thank you for taking the time and helping me move forward.

@samul-1 hey thanks for taking the time and adding context to @KenWhitesell answer. It has helped me think a bit differently about how I approach testing Django and things to consider as my project grows.

1 Like