vendredi 29 juillet 2016

What is the most idiomatic way in Go to test code which has dependency on structure with big amount of methods?

Lets say I have a UserRepository struct which incapsulates logic for interacting with a database. This struct has a set of methods like:

  • findAll()
  • findById()
  • findByName()
  • save()
  • and so on....

There is another struct (let's call it UserService for instance) which depends on UserRepository struct.

To test UserService I need to mock functionality of UserRepository. The only way I know to do this is to provide the interface for UserRepository and make UserService be dependent on it instead of UserRepository struct. It will allow to create a mocked implementation of interface and set it as dependency of UserService in the test.

What is the most idiomatic way to do it?

1) If UserService depends only on 1 UserRepository's method (let's say findAll) - should I still define an interface which will have all repository methods or it's better to define a separate interface for this method only and use it as a dependency of UserService? If so, what is the best name for it (interface)? If another struct will depend on findAll() and findById() methods should I again create another interface?

2) Where is a best place to store mocks for these interfaces? Is it possible to reuse them? Or for tests of different structs I will need redefine the mocks?

P.S. as for me unit tests is a very important part of the project. I would like to make them as readable as possible avoiding boilerplate code and focusing on their logic. So creating several mock implementations for same interfaces in different test files looks for me a bad option since it makes test code less readable.

Aucun commentaire:

Enregistrer un commentaire