-
-
Save JeffreyWay/4560401 to your computer and use it in GitHub Desktop.
<?php | |
class EloquentDogRepository implements DogRepository { | |
public function findBy($config) | |
{ | |
return Dog::where(function($query) use($config) { | |
foreach($config as $key => $value) { | |
$query->where($key, '=', $value); | |
} | |
})->get(); | |
} | |
} |
I'd abstract away the closure into a dogFinder
method on the EloquentDogRepository
, partially mock that class and test them both independently.
Something like this:
<?php
class EloquentDogRepository implements DogRepository {
public function findBy($config)
{
return Dog::where(function($query) use ($config, &$this)
{
$this->dogFinder($query, $config);
})->get();
}
public function dogFinder($query, $config)
{
foreach($config as $key => $value) {
$query->where($key, '=', $value);
}
}
}
That way, when testing, you can chuck a Mockery::mock
at $query
to suitably test it. It's not IDEAL, but is much better than having a full testing database set up :-)
Tests should be optimised for speed and simplicity. Introducing a database means you either need to mess around with dumping / clearing the database after every test, which makes it all painfully slow and boring, or you need to use your tests to set up state, which is stupid, since tests should be able to be run in parallel and/or independently of each other.
Very well put. :)
I prefer to use the opposite direction. In my tests I'm using another fresh database. Yes, I spend time in clearing the database, but I'm as close as possible to the real situation. When the project/test is simple, it's nice to use mocks, but if you have some complex integration test, which perform dozen of things in the data is better to use a real database. If the database is completely new for the tests you still can run the tests independently/parallel and leave the original one.
Here's a quickie example for fetching from a DB, based upon config in the querystring.
If you only mock
findBy
, then you never test to make sure that the method works as expected. Would you simply not test that?