Unit Testing – How to Unit Test Service Methods Using Repository Methods

designphpunittestingunit testing

For service methods that call repository methods to interact with database how could I unit test these service methods?

For example,

public function updateSlideshow($data){
    // do some logic and method calls (I can test those methods,
    // but for this method that call repository ...)

    $r = $this->blockRepo->update($data, $config, $slides);
}

How can I check that this method work correctly or at least send right data to update method?

And what about a scenario that method first fetch data from repository and do logic on it?

Best Answer

Assuming you are using dependency injection, then this situation is easily solved. You will be injecting blockRepo into the class/module containing updateSlideshow. So in a live environment, you inject a version of blockRepo that talks to a DB. In a test environment, you inject a version that mocks this behaviour, eg reads/writes to local variables, rather than a DB, allowing you to simulate various DB data states for the various tests.

Related Topic