Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Should model classes be tested?

Should model classes be tested?

Model classes does not contain logic, but usually contains some logic in the constructor for initialization.

These class are also shared, therefore it a very important that these class initializes correctly.

What is the standard for testing, should model classes be tested? Or the class that make use of them have responsibility to test them?

like image 950
RayOldProf Avatar asked Sep 24 '15 14:09

RayOldProf


2 Answers

If you care whether code works or not, it should be tested. That applies to all code.

Given that, if your model code is getting exercised when you run other tests, it may not be necessary to have tests specific to your models. However, tests are relatively cheap to write and potentially pay off big dividends, so there's no reason not to write a few quick tests for your models.

like image 146
Bryan Oakley Avatar answered Sep 27 '22 17:09

Bryan Oakley


The point is model classes should contain all the logic, according to Model-View-Controller design pattern. Remember -

Thinner views, thin controllers, fat models.

Tutorial

So, by that principle all business logic should be contained in the models. Thereby, models should be thoroughly tested. Besides, data is the most important component in any web project. Thereby, ensuring models have sufficient validations, and they don't allow junk data into db is extremely crucial.

That's what MVC says. Although I agree that trying to fit everything into MVC constructs is a very common antipattern. An even better approach would be to use distinct classes to maintain business logic which don't fall into any MVC constructs, although they must be encapsulated in models too.

Besides, as far as testing is concerned is general, I believe any working piece of code should have atleast modest test suite for them. Tests are working specifications of the code or rather they should be. They guides some else on what your code is doing, how to change it without breaking anything.

Note:- Don't test your libraries though i.e. don't test django code or mongoengine

like image 38
hspandher Avatar answered Sep 27 '22 17:09

hspandher