Mock private method in the same class that is being tested

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

    To mock the private method, you need powermock
    The sample code will be like this, but I haven't run it.

        import org.mockito.Mockito;
        import org.powermock.api.mockito.PowerMockito;
        import org.powermock.modules.junit4.PowerMockRunner;
    
        @RunWith (PowerMockRunner.class)
        public class MyClassTest  {
    
            @Test
            public void test_MyClass_methodA_enters_if_condition()  {
                final MyClass myClass = Mockito.mock (MyClass.class);
                CustomObject object1 = new CustomObject("input1");
                CustomObject object2 = new CustomObject("input2");
                Mockito.when (myClass.methodB(object1, object2)).thenReturn (true);
                Mockito.when (myClass.methodA(object1, object2)).thenCallRealMethod ();
    
                assertEquals(myClass.methodA(object1, object2), "Result");
            }
        }
    

提交回复
热议问题