java PowerMock:来自父类的存根方法
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/32748884/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
PowerMock: stub methods from parent class
提问by jchitel
I'm using PowerMock and I'd like to know how to keep all behavior of the child class, but stub super
calls that may be overriden by the child.
我正在使用 PowerMock,我想知道如何保留子类的所有行为,但super
可能会被子类覆盖的存根调用。
Say I have this class:
说我有这门课:
public class A {
public String someMethod() {
return "I don't want to see this value";
}
}
and a sub class:
和一个子类:
public class B extends A {
@Override
public String someMethod() {
return super.someMethod() + ", but I want to see this one";
}
}
How do I stub the call to super.someMethod()
?
我如何存根呼叫super.someMethod()
?
I've tried
我试过了
@Test
public void test() {
B spy = PowerMockito.spy(new B());
PowerMockito.doReturn("value").when((A)spy).someMethod();
assertEquals("value, but I want to see this one", spi.someMethod());
}
回答by Steve
You can try suppressing the methods from the Parent class,
您可以尝试抑制父类中的方法,
PowerMockito.suppress(methodsDeclaredIn(A.class));
Here's an article on Stubbing, suppressing and replacing with PowerMock that might be of some use.
这是一篇关于 Stubbing、Suppressing 和 Replace with PowerMock 的文章,可能会有用。
https://www.jayway.com/2013/03/05/beyond-mocking-with-powermock/
https://www.jayway.com/2013/03/05/beyond-mocking-with-powermock/
回答by DustinB
Don't forget to add @PrepareForTest({ParentClassToSupress.class})
on your test class. Then you can do as Steve suggests and suppress methods in the parent: PowerMockito.suppress(methodsDeclaredIn(ParentClassToSupress.class));
不要忘记添加@PrepareForTest({ParentClassToSupress.class})
您的测试类。然后你可以按照史蒂夫的建议去做,并在父级中抑制方法:PowerMockito.suppress(methodsDeclaredIn(ParentClassToSupress.class));
回答by Keith
The cast you're attempting is not going to work as you are expecting. However, I think you have a couple of options to get around this, certainly with PowerMockito.
您尝试的演员表不会像您期望的那样工作。但是,我认为您有几种选择可以解决这个问题,当然是使用 PowerMockito。
Take a look at this StackOverflow answer.
看看这个StackOverflow 答案。