Summer Sale! All accounts are 50% off this week.

marbobo's avatar
Level 12

Unit Testing a Model Class

Hi, do you guys do a unit test on your model class? like if you have a unit test on your service and repository class and you also have a feature test on your controller. do you still need test on your models?

0 likes
4 replies
Tray2's avatar

I usually don't test relationships in a unit test but rather in a feature or end to end test. The only thing I usually test in my models is the set and get attributes and any other methods that is no relationships.

2 likes
martinbean's avatar
Level 80

@kevdev I seldom unit test model classes as many model methods interact with a database, and a unit test shouldn’t interact with external services like a database.

For model methods, I’ll usually create a separate Integration directory and namespace in my tests directory, and test method methods in there. I won’t go to the point where I’m testing relationship methods though, because that’s not really testing anything useful. Eloquent will already have tests for relationship methods.

Testing a has-many relation method returns a HasMany instance just isn’t that helpful to me. Something else is going to break if I change that to a HasOne or something…

1 like
Tray2's avatar

@sagormax I don't test fillables, I test that a valid recerd can be saved in the database, if I need to cast something then I usually test that as well in the feature test.

I've noticed that I write less and less code in my models, and let the database handle those things instead.

Please or to participate in this conversation.