本文介绍了最后的方法嘲笑的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我需要使用mockito使用final方法模拟一些类。我写过类似的东西
I need mock some class with final method using mockito. I have wrote something like this
@Test
public void test() {
B b = mock(B.class);
doReturn("bar called").when(b).bar();
assertEquals("must be \"overrided\"", "bar called", b.bar());
//bla-bla
}
class B {
public final String bar() {
return "fail";
}
}
但它失败了。
我尝试了一些hack并且它有效。
But it fails.I tried some "hack" and it works.
@Test
public void hackTest() {
class NewB extends B {
public String barForTest() {
return bar();
}
}
NewB b = mock(NewB.class);
doReturn("bar called").when(b).barForTest();
assertEquals("must be \"overrided\"", "bar called", b.barForTest());
}
它有效,但闻起来。
那么,哪里是正确的方式?
So, Where is the right way?
谢谢。
推荐答案
Mockito中不支持模拟最终方法。
There is no support for mocking final methods in Mockito.
正如Jon Skeet评论的那样,你应该寻找一种方法来避免依赖于最后的方法。也就是说,通过字节码操作有一些方法(例如使用PowerMock)
As Jon Skeet commented you should be looking for a way to avoid the dependency on the final method. That said, there are some ways out through bytecode manipulation (e.g. with PowerMock)
A 将详细解释事情。
A comparison between Mockito and PowerMock will explain things in detail.
这篇关于最后的方法嘲笑的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!