Mock private method in the same class that is being tested

后端 未结 5 1512
余生分开走
余生分开走 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:01

    To give the answer you asked for (using JMockit's partial mocking):

    public class MyClassTest
    {
        @Tested MyClass myClass;
    
        @Test
        public void test_MyClass_methodA_enters_if_condition() {
            final CustomObject object1 = new CustomObject("input1");
            final CustomObject object2 = new CustomObject("input2");
    
            new NonStrictExpectations(myClass) {{
                invoke(myClass, "methodB", object1, object2); result = true;
            }};
    
            assertEquals("Result", myClass.methodA(object1, object2));
        }
    
        @Test
        public void test_MyClass_methodA_skips_if_condition() {
            final CustomObject object1 = new CustomObject("input1");
            final CustomObject object2 = new CustomObject("input2");
    
            new NonStrictExpectations(myClass) {{
                invoke(myClass, "methodB", object1, object2); result = false;
            }};
    
            assertEquals("Different Result", myClass.methodA(object1, object2));
        }
    }
    

    However, I would not recommend doing it like that. In general, private methods should not be mocked. Instead, mock the actual external dependency of your unit under test (the CustomObject in this case):

    public class MyTestClass
    {
        @Tested MyClass myClass;
        @Mocked CustomObject object1;
        @Mocked CustomObject object2;
    
        @Test
        public void test_MyClass_methodA_enters_if_condition() {
            new NonStrictExpectations() {{
                Something thing = new Something();
                object1.getSomething(); result = thing;
                object2.getSomething(); result = thing;
            }};
    
            assertEquals("Result", myClass.methodA(object1, object2));
        }
    
        @Test
        public void test_MyClass_methodA_skips_if_condition() {
            new NonStrictExpectations() {{
                object1.getSomething(); result = new Something();
                object2.getSomething(); result = new Something();
            }};
    
            assertEquals("Different Result", myClass.methodA(object1, object2));
        }
    }
    

提交回复
热议问题