简体   繁体   English

在Java中模拟链式调用的最佳解决方案

[英]best solution for mocking chained calls in Java

I have the following code: 我有以下代码:

handler = NodeHandler.getINodeHandler(localZone).getITspPlatformHandler().getITspProcessorManagementHandler();

I mocked this out this way: 我这样嘲笑:

mockStatic(NodeHandler.class);
INodeHandler iNodeHandler = mock(INodeHandler.class,Mockito.RETURNS_DEEP_STUBS);
when(NodeHandler.getINodeHandler(localZone)).thenReturn(iNodeHandler);
ITspProcessorManagementHandler iTspProcessorManagementHandler =mock(ITspProcessorManagementHandler.class,Mockito.RETURNS_DEEP_STUBS);
when(iNodeHandler.getITspPlatformHandler().getITspProcessorManagementHandler()).thenReturn(iTspProcessorManagementHandler);

After a few row of code an another chained method call comes: 在几行代码之后,另一个链式方法调用来了:

ITspTrafficProcessor processor = NodeHandler.getINodeHandler(localZone, localUI).getITspPlatformHandler().getITspProcessorManagementHandler()
                .getITspProcessorHandler(procs[i]).getITspTrafficProcessorHandler(0).getAttributes();

And i mocked this out this way: 我这样嘲笑这个:

when(NodeHandler.getINodeHandler(localZone,UI.CORBA)).thenReturn(iNodeHandler);
when(iNodeHandler.getITspPlatformHandler().getITspProcessorManagementHandler()(+1+).getITspProcessorHandler(anyString())
            .getITspTrafficProcessorHandler(anyInt()).getAttributes()).thenReturn(null);

So my question is that, i can not find a better solution than this, because the problem is if i tell the mockito to return null to the handler instead of iTspProcessorManagementHandler then i get a nullpointer exception at (+1+), but if i do the following changes to my code: 所以我的问题是,我找不到比这更好的解决方案,因为问题是如果我告诉mockito将null返回到处理程序而不是iTspProcessorManagementHandler然后我在(+ 1 +)得到一个nullpointer异常,但如果我对我的代码进行以下更改:

INodeHandler iNodeHandler = mock(INodeHandler.class,Mockito.RETURNS_MOCKS);

Than mockito mocks out every method call, and my when-thenReturn statements does not returns what i want for example null. 比mockito模拟每个方法调用,我的when-thenReturn语句不返回我想要的例如null。 So any advice to do a better solution???? 那么任何建议做一个更好的解决方案????

Messy mocking like that is an indication that you could improve abstraction. 像这样的凌乱嘲弄表明你可以改进抽象。 I'd consider encapsulating that particular logic in a helper interface/class, or to inject the expected type returned by the "trainwreck" to the method/class. 我会考虑将该特定逻辑封装在辅助接口/类中,或者将“trainwreck”返回的预期类型注入方法/类。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM