14

Mockito如何mock一条链式调用

 4 years ago
source link: https://www.pkslow.com/archives/mockito-chained-methods
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

在写单元测试的时候,不免可能需要mock一些对象出来,并且mock一些方法调用去返回一个自己想要的对象。一般的使用是这样的:

FinalPumpkin pumpkin = mock(FinalPumpkin.class);
when(pumpkin.getName()).thenReturn("www.pkslow.com");

这样我们便可以自定义这个类 getName() 方法的返回,以达到我们测试特定情况的需要。

但假设可能我们要影响的是下面这样的返回结果呢?

pumpkin.getWeb().getFactory().getContainer().getHostname()

那可能我们就要先mock四个对象出来,然后再一层层mock方法的返回结果了。如下:

FinalPumpkin pumpkin = mock(FinalPumpkin.class);
Web web = mock(Web.class);
Factory factory = mock(Factory.class);
Container container = mock(Container.class);

when(pumpkin.getWeb()).thenReturn(web);
when(web.getFactory()).thenReturn(factory);
when(factory.getContainer()).thenReturn(container);
when(container.getHostname()).thenReturn("www.pkslow.com");

这可够麻烦的。

幸好 Mockito 也想到这种情况,提供了解决办法, mock 对象的时候增加参数 RETURNS_DEEP_STUBS 可以实现如下简洁办法:

@Test
public void testChainMethod() {
  FinalPumpkin pumpkin = mock(FinalPumpkin.class, RETURNS_DEEP_STUBS);
  when(pumpkin.getWeb().getFactory().getContainer().getHostname())
    .thenReturn("www.pkslow.com");
  verify(pumpkin.getWeb(), atLeastOnce());
}

注意:如果有返回值为泛型,会报 ClassCastException 的错误,这时需要拆开,把返回类型强制转换为 Object 类。

欢迎访问 南瓜慢说 www.pkslow.com 获取更多精彩文章!

欢迎关注微信公众号< 南瓜慢说 >,将持续为你更新...

ENvAvm2.jpg!web

多读书,多分享;多写作,多整理。


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK