1

I have a class like this: Notice it does not have a default constructor either and inherits from some other class

public class IdentifierManager : IdentifierManagerBase
{
    public IdentifierManager(ILogger<IdentifierManager> logger, IMemoryCache cache)
    {
        this.logger = logger;
        this.cache = cache;
        cacheSemaphore = new SemaphoreSlim(1, 1);
    }
    
    protected override string DoSomething()
    {
        return "This is the method I want to test...";
    }   
}

So I want to write a unit test for that DoSomething() method.

And here is the class it inherits from:

public abstract class IdentifierManagerBase : IIdentifierManager
{
    // bunch of other public methods 
    
    protected abstract string DoSomething();
}

So how do I test that protected DoSomething() method? I saw this answer Unit testing C# protected methods and this blog post https://codingjourneyman.com/2015/07/27/unit-tests-and-protected-methods/

and tried to do something like this: but having trouble with constructors

public class IdentifierManager_Exposed: IdentifierManager
{
    public string DoSomething()
    {
        return base.DoSomething();
    }
}

and then in the test if my test class is inheriting from the IdentifierManager_Exposed one but like I said I can't figure out how to deal with the constructor parameters.

2 Answers2

1

Keep in mind that your testing focuses on behavior rather than methods. Private and protected methods within a class remain outside the scope of the public interface, thus not exposing public behavior. As a result, these private methods are inherently tested through the test cases that verify the behavior of your public interface. This is discussed in more detail in the following question: Should Private/Protected methods be under unit test?

Behnam
  • 337
  • 1
  • 6
  • Related Software Engineering question: [How do you unit test private methods?](https://softwareengineering.stackexchange.com/q/100959/118878), which basically says what this answer says. – Greg Burghardt Aug 16 '23 at 15:25
0

To be able to test the protected method, i would recommend you to use the internalsVisibleTo, over the other method.

With regards to the complex initialization of the IdentifierManagerBase, you do not have that many options. Either initialize it (how complex it might be) or move the internal logic of the DoSomething to a seperate class you then can test against, and use a reference to inside the IdentifierManager class.

Henrik Gering
  • 1,769
  • 16
  • 29