How can I test a method that calls the protected (unwanted) methods of the parent class?

I am stuck in a very strange case. I have a specific code that I need to check. There he is:

public class A {

    /*
     * The real method of real class is so big that I just don't want to test it.
     * That why I use throwing an exception.
     */
    protected void method(Integer result) {
        throw new RuntimeException("Oops!");
    }

    protected <T> T generifiedMethod(String s, T type) {
        throw new RuntimeException("Oops!");
    }

    protected void mainMethod(Integer value) {
        throw new RuntimeException("Oops!");
    }
}

I also have a child class:

public class B extends A {

    @Override
    protected void mainMethod(Integer value) {
        if (value == 100500) {
            Integer result = super.generifiedMethod("abc", 100);
            super.method(result);
        }
        super.mainMethod(value);
    }
}

I need to cover the child class with tests.

I tried to combine a lot with PowerMockito, but none of them can test the call to the protected methods of the parent class. In addition, I have a restriction on using only Mockito, PowerMockito, and TestNG.

Here is my test code (one of the options):

@Test
public void should_invoke_parent_logic_methods_of_A_class() throws Exception {

    /* Given */
    A aSpy = PowerMockito.spy(new A());

    PowerMockito.doReturn(250).when(aSpy, "generifiedMethod", "abc", 100);
    PowerMockito.doNothing().when(aSpy, "method", 250);
    PowerMockito.suppress(method(A.class, "mainMethod", Integer.class));

    /* When */
    aSpy.mainMethod(100500);

    /* Then */
    /**
     * Here I need to verify invocation of all methods of class A (generifiedMethod(), method(),
     * and mainMethod()). But I don't need them to be invoked because their logic is unwanted
     * to be tested in case of tests for class B.
     */
}

I would appreciate any suggestions for testing class B. Thanks.

Update

If I add to the section then this code

Mockito.verify(aSpy, times(3)).mainMethod(100500);
Mockito.verify(aSpy, times(1)).generifiedMethod("abc", 100);
Mockito.verify(aSpy, times(1)).method(250);

The following error message appears:

Wanted but not invoked:
a.generifiedMethod("abc", 100);
+4
3

? A B. , .

, doCallRealMethod() , , .

+1

, mainMethod B. , B, A. :

/* Given */
B b = Mockito.mock(B.class);

//use this to skip the method execution
Mockito.doNothing().when(b).generifiedMethod(Mockito.anyString(), Mockito.any());
Mockito.doNothing().when(b).method(Mockito.anyInt());

//or use this to return whatever you want when the methods are called
Mockito.doReturn(new Object()).when(b).method(Mockito.anyInt());
Mockito.doReturn(new Object()).when(b).generifiedMethod(Mockito.anyString(), Mockito.any());

mainMethod B, , .

0

, , , .

A, :

  • , method, generifiedMethod mainMethod
  • reset
  • .

Junit TestNG. , , , , , stub, A.

0

All Articles