Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

CLab's avatar
Level 3

Unit test with models?

Can/Should unit tests be made with instances of models created to database or should these be feature tests?

Basically I created a custom rule and wanted to test it. My rule checks the model instance if it has some value in a JSON column. I searched for articles for testing custom validation rule and came across articles like https://nickescobedo.com/1262/how-to-write-tests-for-a-custom-laravel-validation-rule which use unit tests for testing custom validation rules.

0 likes
8 replies
fylzero's avatar

@clab I know ppl will argue this, but I am of the firm opinion that once you touch the database it is no longer a unit test. Should be a feature test. Totally imo.

1 like
CLab's avatar
Level 3

@drewdan thanks for the response. I also believe it should be a feature test, but since I am a beginner I wanted to know the thoughts of some senior devs.

tykus's avatar

@CLab does your test need to create a model instance; or can it also work on an in-memory instance?

CLab's avatar
Level 3

@tykus Not sure I understand completely. My test needs to create a model using factory:

$post = Post::factory()->create();

i.e. it needs to be in a db. The post has a field with a json array. The validation checks if the json array column in the $post has a specific field. So it needs to do a DB query to check if it exists.

For tests I use an in memory database i.e. sqlite as defined in the phpunit.xml file.

tykus's avatar

@CLab I meant, can you use a factory to make a Post instead

$post = Post::factory()->make();

However, it needs to be in a db means this is not relevant. Anyway, if your question is about semantics of Unit vs. Feature testing; this is moot - since you are not testing a Unit of code anyway.

CLab's avatar
Level 3

@tykus I see your point. I think it comes down to the definition of unit. Even though my test is for a single rule it is not counted as a unit because it uses several components of my application. Am I correct in my understanding?

tykus's avatar

@CLab yes, exactly. TBH, I wouldn't get hung up on definitions. If you are testing your application sufficiently to give you/your client confidence that it performs as expected; then you're on the right track.

I would rather see an Integration test misclassified as a Unit test than no test at all!

CLab's avatar
Level 3

@tykus Thanks - I appreciate your candidness. Since my project will most likely be inherited by some other dev I would like to follow basic guidelines which is why I ask here.

Please or to participate in this conversation.