How to unit test private methods in BDD / TDD?

前端 未结 12 991
攒了一身酷
攒了一身酷 2020-12-15 22:03

I am trying to program according to Behavior Driven Development, which states that no line of code should be written without writing failing unit test first.

My ques

12条回答
  •  温柔的废话
    2020-12-15 22:13

    I agree with the point that has been made about not testing private methods per se and that tests should be written against the public API, but there is another option you haven't listed above.

    You could make the methods protected then derive from the class under test. You can expose the base protected method with a public method on the derived class, for example,

    public class TestableClassToTest : ClassToTest
    {
        public new void MethodToTest() 
        { 
            base.MethodToTest(); 
        } 
    }
    

    You might be using this Extract and Override pattern already to override virtual properties of the base class for dependency injection, in which case this may be a viable option for you.

提交回复
热议问题