3

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?

mohsenJsh
  • 1,365

2 Answers2

5

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.

David Arno
  • 39,599
  • 9
  • 94
  • 129
1

Don't unit test them, at least at first. Use an integration test which brings up an empty database with your DDL loaded, runs this method with some inputs, and asserts on the result data or result behavior.

Having that integration test in place will be a good stepping stone for creating a test double. Code your db-interacting code against an interface which your db class implements. You can then make a test double implementation that uses a Map locally to provide the same interface. That double can be passed along to other pieces of code which depend on database functionality. The integration test you wrote for the full database version can be used to cross-check that the test double exposes correct behavior.

Daenyth
  • 8,147