I’ve designed an application that uses the repository pattern, and then a separate service layer such as this:
public class RegistrationService: IRegistrationService
{
public void Register(User user)
{
IRepository<User> userRepository = new UserRepository();
// add user, etc
}
}
As you can see, I am instantiating my repository inside of the Register method. Now as I want to write some unit tests, I can’t really get to it and replace it with a fake repository can I?
I don’t want to add the repository as class variable though (and set it through a constructor) because I think that would make my code “smelly” (not all repositories are needed for all methods, and I don’t need the calling layer to know about repositories etc.).
Suggestions?
You need to use Dependency Injection. UserRepository is a dependency of your RegistrationService class. To make your classes properly unit testable (i.e. in isolation of their dependencies), you need to “invert” what controls your dependency creation. Currently, you have direct control, and are creating them internally. Just invert that control, and allow something external (such as an IoC container like Castle Windsor) inject them:
I think I forgot to add. Once you allow your dependencies to be injected, you open up the possability of them being mockable. Since your RegistrationService now takes its dependent user repository as input to its constructor, you can create a mock repository and pass that in, instead of an actual repository.