I've created a package that manipulates eloquent models, and I've created test cases for it.
The package is supposed to call save() or delete() for the models, at some point, which would attempt to hit the database.
Actual Database approach
As first attempt I tried this approach and also this. The point is that in the context of a package (even using orchestra/testbench) I'd need to configure a database and migrations. Since the package itself does not have any model (but I've created a dummy model for test purposes) I see this approach as possibly overkill. In any case, I'd still accept to setup a prepared sqlite db in memory, which I also tried but could not make it work (It was attempting to use forge connection instead sqlite and I could not make it access another connection. I may provide details on what I did for it).
Mocking approach
Another possible attempt (as per my limited understanding on this) is to partially mock the model. But after I mocked it, it would not know how to handle other calls such as fill(), for which I was willing the common behavior, but I received a method not found exception.
Method override approach
Given that these two possible attempts went bad, I defaulted to a third possible approach which worked for me, but I'm honestly not sure if this is the way to go about it.
In order to avoid test failure due to lack of database when calling save() or delete() methods, I overrided them (full source code here) :
class DummyContact extends Model
{
// ...
public function save(array $options = [])
{
$this->exists = true;
$this->wasRecentlyCreated = true;
}
public function delete()
{
$this->exists = false;
$this->wasRecentlyCreated = false;
}
}
This way, I'm able to test the following code (full source here):
public function unifyOnBase()
{
$mergeModel = $this->merge();
$this->modelA->fill($mergeModel->toArray());
$this->modelA->save();
$this->modelB->delete();
return $this->modelA;
}
So my question is, is this approach acceptable? (I think it is fair, I don't see exceptional pitfalls, but I suspect there exist more elegant approaches). In case there are suggested approaches, like Mocking or using an actual DB for running the tests, I'd like to know what adaptations should I do to my testing codebase for taking them.
Final but important note: I'm not willing to test models itself, I'm willing to test my code that uses (and thus depends on models).
