最终方法模拟 [英] Final method mocking

查看:32
本文介绍了最终方法模拟的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要使用 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 不支持模拟 final 方法.

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)

Mockito 和 PowerMock 之间的比较会详细解释.

这篇关于最终方法模拟的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆