TheWommies
TheWommies

Reputation: 5072

Unit testing C# refactoring static methods

I have some classes(call it Class A) which I would like to unit test but it uses some classes(call it Class B) with some static methods.

To remove reference to these classes with static methods I have to refactor them to be instance methods and inject into Class A.

Issue is Class A has lots of services(Not only class B) its seems to depend on?

What is the best option in this scenario? Have a constructor that has a lot of parameters that can take in these services?

Or is there something wrong with my design the fact that class A has so many dependencies?

Thanks

Upvotes: 1

Views: 982

Answers (2)

Avner Shahar-Kashtan
Avner Shahar-Kashtan

Reputation: 14700

I would recommend constructor injection, especially if you have a lot of dependencies to inject, only if you're using a Dependency Injection framework like Unity or Ninject. Refactoring an existing code-base to add constructor injection everywhere is usually messy, and probably requires storing all the services in local variables in many base classes just so you can pass them on to classes further down the chain.

What I would do in this case is use some implementation of the ServiceLocator pattern, with a single static ServiceLocator/Container class that you can use to access your non-static services:

IService _service = ServiceLocator.GetService<IService>();

This will require the minimum amount of refactoring in existing code (just replace MyService.DoSomething() with _service.DoSomething(), and still allow you to mock and test your code by replacing the ServiceLocator's internet collection:

ServiceLocator.Register<IService>(myFakeService);

Upvotes: 2

jgauffin
jgauffin

Reputation: 101176

Issue is Class A has lots of services(Not only class B) its seems to depend on?

Several dependencies are usually indicating a code smell. Your class is most likely breaking Single Responsibility Principle.

Try to break down the class into smaller classes.

Unit tests are a good quality indicator. Classes that are hard to test are often violating one or more of the SOLID principles.

What is the best option in this scenario? Have a constructor that has a lot of parameters that can take in these services?

Constructor injection is always the preferred way since it's easy to tell what dependencies a class has.

Upvotes: 5

Related Questions