vendredi 12 juin 2020

PowerMockito - mock abstract class and methods

I'm new to PowerMockito/Mockito and am not very clear on which classes/methods to mock. I need to verify if method2() is being invoked. I'm not able to invoke the base class methods. Below is my abstract class and the test I've written. BaseClass is:

// Cannot edit BaseClass methods

public abstract BaseClass {
    public void test(){
        try {
            method1(); // Can throw exception
        }

        finally{
            method2(); // Need to verify if this method is invoked 
        }

        protected abstract void method1() throws Exception

        protected void method2(){
            ToBeMockedClass.method3();
        }
    }
}

PowerMockito test:

// Code I've written

@PowerMockIgnore({"javax.management.*"})
@PrepareForTest({ToBeMockedClass.class})
public class myNewTest extends PowerMockTestCase {
    private classA classAobj;

    @BeforeMethod
    public void init() throws Exception {
        MockitoAnnotation.initMocks(this);
        mockedClass = PowerMockito.mock(ToBeMockedClass.class);
        classAobj = new classA();
    }

    @Test
    public void testBaseClassInitializeMethod() throws Exception {
        try{
            classAobj.test();
        }
        finally {
            verify(mockedClass, times(1)).methodInMockedClass();
        }
    }

    static class classA extends BaseClass {
        protected classA(){
            super();
        }

    @Override
    static void method1() throws Exception {
        throw new Exception();
    }
}

Aucun commentaire:

Enregistrer un commentaire