Unit testing C# protected methods

后端 未结 6 1206
再見小時候
再見小時候 2020-12-23 15:39

I come from the Java EE world but now I\'m working on a .Net project. In Java when I wanted to test a protected method it was quite easy, just having the test class with the

6条回答
  •  挽巷
    挽巷 (楼主)
    2020-12-23 16:38

    Although the accepted answer is the best one, it didn't solve my problem. Deriving from the protected class polluted my test class with a lot of other stuff. In the end I chose to extract the to-be-tested-logic into a public class and test that. Surely enough this will not work for everyone and might require quite some refactoring, but if you scrolled all the way up to this answer, it might just help you out. :) Here's an example

    Old situation:

    protected class ProtectedClass{
       protected void ProtectedMethod(){
          //logic you wanted to test but can't :(
       }
    }
    

    New situation:

    protected class ProtectedClass{
       private INewPublicClass _newPublicClass;
    
       public ProtectedClass(INewPublicClass newPublicClass) {
          _newPublicClass = newPublicClass;
       }
    
       protected void ProtectedMethod(){
          //the logic you wanted to test has been moved to another class
          _newPublicClass.DoStuff();
       }
    }
    
    public class NewPublicClass : INewPublicClass
    {
       public void DoStuff() {
          //this logic can be tested!
       }
    }
    
    public class NewPublicClassTest
    {
        NewPublicClass _target;
        public void DoStuff_WithoutInput_ShouldSucceed() {
            //Arrange test and call the method with the logic you want to test
            _target.DoStuff();
        }
    }
    

提交回复
热议问题