How to unit test private methods in BDD / TDD?

前端 未结 12 1009
攒了一身酷
攒了一身酷 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:18

    I've been fighting with it for over 1 month, but found the answer:

            var objectOfPrivateMethod = new ObjectOfPrivateMethod(); //yes here is contructor
            object[] arguments = {  }; // here as Object you provide arguments
    
            var extractedPrivateMethod = typeof(ObjectOfPrivateMethod).GetMethod("Name_Of_Private_Method", BindingFlags.NonPublic|BindingFlags.Static); //if fails returns null. delete flag static if it's not static. Returns your method as an object.
            Assert.AreNotEqual(null, extractedPrivateMethod, "Mathod does not exist"); // good to catch if even exists.
    
            object result = extractedPrivateMethod.Invoke(null, arguments); // here as object you'll get return value of your function. change null for object of class where is method, if your method is not static 
    

    that's all.

提交回复
热议问题