Mock private method in the same class that is being tested

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

    import org.easymock.EasyMock;
    import org.junit.Assert;
    import org.junit.Before;
    import org.junit.Test;
    import org.junit.runner.RunWith;
    import org.powermock.api.easymock.PowerMock;
    import org.powermock.core.classloader.annotations.PrepareForTest;
    import org.powermock.modules.junit4.PowerMockRunner;
    
    @RunWith(PowerMockRunner.class)
    @PrepareForTest({ MyClass.class })
    public class MyClassTest {
    
    // Class Under Test
    MyClass cut;
    
    @Before
    public void setUp() {
    
        // Create a new instance of the service under test (SUT).
        cut = new MyClass();
    
        // Common Setup
        // TODO
    }
    
    @Test
    public void testMethodA() throws Exception {
    
        /* Initialization */
        CustomObject object2 = PowerMock.createNiceMock(CustomObject.class);
        CustomObject object1 = PowerMock.createNiceMock(CustomObject.class);
    
        MyClass partialMockCUT = PowerMock.createPartialMock(MyClass.class,
                "methodB");
        long response = 1;
    
        /* Mock Setup */
        PowerMock
                .expectPrivate(partialMockCUT, "methodB",
                        EasyMock.isA(CustomObject.class),
                        EasyMock.isA(CustomObject.class)).andReturn(true)
                .anyTimes();
    
        /* Mock Setup */
    
        /* Activate the Mocks */
        PowerMock.replayAll();
    
        /* Test Method */
    
        String result = partialMockCUT.methodA(object1, object2);
    
        /* Asserts */
        Assert.assertNotNull(result);
        PowerMock.verifyAll();
    
    }
    
    }
    

提交回复
热议问题