Wilson willy
Wilson willy

Reputation: 13

Issues while Unit testing in c#

I have a class Library project which will be consumed by some legacy code and some modernized code. briefly I would like to show what issues I am facing with.

class ClasslibraryService
{
    private Dependency1 _dependency1;
    private Dependency2 _dependency2
    public  ClasslibraryService(Dependency1 dependency)
    {
        _dependency1 = dependency;
         // this dependency2 could be something like logger or Bearer token service which I do not want to expose to consuming application
        _dependency2 = new Dependency2(new Dependency3());
    }
    public int DoSomeOperation()
    {
        var res = _dependency2.DoSomething();
        return _dependency1.DoSomeOperation(res);
    }
} 

So basically I had to new up within constructor without injecting dependency using constructor.

Now while unit test this class , I have created another constructor which takes all dependency through constructor. This is working fine.

But question here is

  1. I know I am violating main objective of unit testing by creating another constructor.Actual code will not be using this constructor. But I could not find any other way too!!
  2. If 1 is not correct solution , please suggest me one solution

TIA

Upvotes: 0

Views: 119

Answers (1)

Ilian
Ilian

Reputation: 5355

I know I am violating main objective of unit testing by creating another constructor.Actual code will not be using this constructor. But I could not find any other way too!!

I know this is heresy for some but I believe there's no hard rule in software development. It's a game of tradeoffs. If it's too expensive to change how your constructor works, you can probably do something like this for now:

public  ClasslibraryService(Dependency1 dependency1, Dependency2 dependency2 = null)
{
    _dependency1 = dependency1;
    _dependency2 = dependency2 ?? new Dependency2(new Dependency3());
}

This introduces a default implementation for real code which can be overridden in unit tests. You can then revisit this code later and make it purer.

Upvotes: 2

Related Questions