Mock private method in the same class that is being tested

后端 未结 5 1575
余生分开走
余生分开走 2021-02-02 14:49

I have a Java class named, MyClass, that I want to test with JUnit. The public method, methodA, that I want to test calls a private method, meth

5条回答
  •  半阙折子戏
    2021-02-02 15:02

    Make methodB a member of a separate class, and have a private reference to that class within MyClass.

    public class MyClass  {
        private MyOtherClass otherObject = new MyOtherClass();
    
        public String methodA(CustomObject object1, CustomObject object2)  {
    
            if(otherObject.methodB(object1, object2))  {
                // Do something.
                return "Result";
            }
    
            // Do something different.
            return "Different Result";
    
        }
    }
    
    class MyOtherClass {
        public boolean methodB(CustomObject custObject1, CustomObject custObject2)  {
            // Yada yada code
        }
    }
    

    Personally, I usually only test public methods and look at coverage reports to ensure that all paths have been visited in my private methods. If I really need to test a private method, that's a smell that requires a refactoring as I have above.

    You could also use reflection, but I'd feel dirty doing that. If you REALLY want the solution to that let me know and I'll add it to this answer.

提交回复
热议问题