简体   繁体   English

无法模拟集合对象

[英]unable to mock collection objects

How do I mock this particular snippet? 如何模拟这个特定的代码段?

Collection<SeoUrlParam> params = getUrlState().getParameters();

I have already mocked 我已经嘲笑了

urlState = mock(UrlState.class);

But I am not sure how to mock the params collection of type which is infact a class 但是我不确定如何模拟实际上是一个类的params集合

You probably don't want to mock the collection. 您可能不想嘲笑该集合。 You want somewhat real data to exist in the collection, and let the code operate it from there instead. 您希望集合中存在一些真实的数据,然后让代码从那里操作它。

Now, with the way your call is laid out, it may be the case that you have two mock objects - one to produce the mock result of getUrlState() , and one to actually return a collection from getParameters() . 现在,按照调用的布局方式,您可能有两个模拟对象-一个用于生成getUrlState()的模拟结果,另一个用于实际从getParameters()返回一个集合。

I'm not sure of the type you're using for either of those calls, so I'll wing it. 我不确定您使用的是哪种类型的电话,因此我将对其进行介绍。 The principle applies, though. 但是,该原理适用。

// Assuming you have the appropriate mock for getUrlState defined
SeoUrlParamHolder parameterHolderMock = mock(SeoUrlParamHolder.class);
Collection<SeoUrlParam> dummyData = Collections.singletonList(new SeoUrlParam());

when(urlState.getUrlState()).thenReturn(parameterHolderMock);
when(parameterHolderMock.getParamters()).thenReturn(dummyData);

Don't mock collection objects. 不要嘲笑集合对象。 Collections themselves don't generally have enough logic in them to make it worthwhile to stub the logic out. 集合本身通常没有足够的逻辑,因此值得对逻辑进行存根。

Treat your collections as value objects, and create real collections as needed. 将您的收藏视为价值对象,并根据需要创建真实的收藏。 If you want to mock the individual objects inside the collection, that's fine, and a practice that I thoroughly recommend. 如果您要模拟集合中的单个对象,那很好,我强烈建议您这样做。

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

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