如何测试调用父类受保护(不希望)方法的方法?

4

我遇到了一个非常奇怪的问题。 我有一些需要测试的特定代码。 这是它:

public class A {

    /*
     * The real method of real class is so big that I just don't want to test it.
     * That's 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!");
    }
}

我也有一个子类:
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);
    }
}

我需要为子类编写测试。

我尝试了很多与PowerMockito有关的组合,但是没有一种方法能够验证父类的受保护方法的调用。此外,我只能使用Mockito、PowerMockito和TestNG。

下面是我的测试代码(其中之一):

@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.
     */
}

我希望您能提供关于如何测试B类的任何建议。谢谢。

更新

如果我在Then部分添加以下代码:

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

它给我以下错误信息:

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

添加 Mockito.verify(aSpy, times(3)).mainMethod(100500); 将会导致编译错误,因为 mainMethod() 是受保护的! - Farrukh Chishti
2个回答

2

您是否考虑过改变类的设计,使用组合而不是继承?这样,您就可以轻松地模拟/监视A类的实例,并将其注入B类的实例中。在这种情况下,您将能够配置所需的任何行为。

我真的不确定doCallRealMethod()是否适用于您,因为您只能选择模拟方法或调用实际方法,而不能同时进行两者。


-1

如果我理解正确的话,您想要测试类B中的'mainMethod'方法。因此,您应该模拟一个来自类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());

然后你可以从B中调用mainMethod,已经知道其他方法将返回什么。


可能不行,因为这些方法是受保护的,测试无法访问它们。 - Adriaan Koster

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接