【问题标题】:Why can BDDMockito not resolve types in this case?为什么在这种情况下 BDDMockito 不能解析类型?
【发布时间】:2017-04-03 03:07:42
【问题描述】:

考虑DynamoDB's QueryApi。通过一系列(不幸的?)箍,

ItemCollection<QueryOutcome>>

最终等同于

Iterable<Item>

我知道这一点,因为我能做到:

public PuppyDog getPuppy(final String personGuid, final String name) {
    final QuerySpec spec = new QuerySpec()
            .withKeyConditionExpression("#d = :guid and #n = :name")
            .withNameMap(new NameMap().with("#d", "guid").with("#n", "name"))
            .withValueMap(new ValueMap().withString(":guid", personGuid).withString(":name", name));
    return getDog(index.query(spec));
}

private PuppyDog getDog(final Iterable<Item> itemCollection) {
    // http://stackoverflow.com/questions/23932061/convert-iterable-to-stream-using-java-8-jdk
    return StreamSupport.stream(itemCollection.spliterator(), false)
    .map(this::createDogFor)
    // it would be a little weird to find more than 1, but not sure what to do if so.
    .findAny().orElse(new PuppyDog());
}

但是当我尝试使用 BDDMockito 在 Mockito 中编写测试时:

@Test
public void canGetPuppyDogByPersonGuidAndName() {
    final PuppyDog dawg = getPuppyDog();
    final ArgumentCaptor<QuerySpec> captor = ArgumentCaptor.forClass(QuerySpec.class);
    final ItemCollection<QueryOutcome> items = mock(ItemCollection.class);
    given(query.query(captor.capture())).willReturn(items);
}

当我尝试将 items 设为 Iterable 时,编译器会报错。

为什么拒绝?

【问题讨论】:

    标签: java-8 mockito amazon-dynamodb


    【解决方案1】:

    不是因为 BDDMockito。 Dis 因为 ItemCollection&lt;QueryOutcome&gt; 根本无法安全地转换成 Iterable&lt;Item&gt;。它可以转换为Iterable&lt;QueryOutcome&gt; 甚至Iterable&lt;? extends Item&gt;,但不能转换为Iterable&lt;Item&gt;

    否则你可以这样做:

    final ItemCollection<QueryOutcome> items = mock(ItemCollection.class);
    Collection<Item> yourItemCollection = items;
    yourItemCollection.add(itemThatIsNotAQueryOutcome);  // violating safety of items
    

    另见:

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-08-15
      • 2016-07-29
      • 1970-01-01
      • 1970-01-01
      • 2022-11-27
      • 2011-04-27
      相关资源
      最近更新 更多