java如何中断父类方法_java – 如何测试调用父类的受保护(不需要)方法的方法?...

我陷入了一个非常奇怪的情况.

我有一些我需要测试的特定代码.

这里是:

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 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);

最佳答案 您是否考虑使用variant来更改类的设计并使用组合而不是继承?

然后,您将能够模拟/侦察A类的实例并将其注入到B类的实例中.

在这种情况下,您将能够配置您需要的任何行为.

我真的不确定doCallRealMethod()会为你制作技巧,因为你可以选择模拟方法或调用实际方法,但不能同时使用.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值