gpt4 book ai didi

java - final方法模拟

转载 作者:IT老高 更新时间:2023-10-28 20:23:30 25 4
gpt4 key购买 nike

我需要使用 mockito 模拟一些带有 final 方法的类。我写了这样的东西

@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”并且它有效。

   @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());
}

它有效,但“有味道”。

那么,正确的方法在哪里?

谢谢。

最佳答案

来自 Mockito FAQ :

What are the limitations of Mockito

  • Cannot mock final methods - their real behavior is executed without any exception. Mockito cannot warn you about mocking final methods so be vigilant.

关于java - final方法模拟,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3793791/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com