【问题标题】:Is it possible for Mockito.when(X).thenReturn(Y) to return a Set<Optional<MyClass>>?Mockito.when(X).thenReturn(Y) 是否可以返回 Set<Optional<MyClass>>?
【发布时间】:2021-08-03 11:34:27
【问题描述】:

要点

我正在使用 Spring Boot、JUnit5 和 Mockito 编写一些测试。尽我所能,我不知道如何让它返回一组可选值。我已经尽我所能搜索了网络和 SO。

背景

我有一个 JPA Repo 方法,它为它的一个查询方法返回一个 Set。除了这个之外,我可以测试与它们所调用的特定服务相关的所有其他查询方法。

当 repo 返回单个项目时,我使用:

MyClass myObj = new MyClass();
Mockito.when(repo.findByX(X)).thenReturn(Optional.of(myObj));

我想要什么

类似的东西:

Mockito.when(repository.findAllByX(X)).thenReturn(Set(Optional.of(myObj)));

出于测试目的,Set 实际上只包含单个对象,但鉴于 repo 方法的约束,它必须是一个 Set 而不能只是对象本身。

恳求

到目前为止,Mockito 为我提供了很好的服务,但我一遍又一遍地遇到问题,即模拟 repo 意味着实际上不会保存任何内容(因此自动生成的 id 不起作用)。如果它可以保存对模拟存储库的更改,那将使生活变得更加轻松。所以,如果有更好的方法来测试修改存储库的服务,我很想知道。

感谢您的帮助和指导。

【问题讨论】:

  • 试试Set.of(Optional.of(myObj))
  • @StefanGolubović 试过了;收到以下错误:"Cannot resolve method 'of' in 'Set'"。我猜,Set 并不像 Optional 那样特别。
  • 您使用的是哪个版本的 Java?您是否尝试过创建一个集合然后返回它?例如:Set&lt;Optional&lt;MyClass&gt;&gt; set = new HashSet&lt;&gt;(); set.add(Optional.of(myObj)); Mockito.when(...).thenReturn(set);。或any other way.
  • 这行得通,我的朋友!谢谢!把它变成一个答案,我会接受它。

标签: spring testing mockito set


【解决方案1】:

这是可能的。您需要做的就是创建一个集合并将其作为参数传递。

如果您使用的是 Java 9+,则可以使用 of 工厂方法来创建集合。

Mockito.when(repository.findAllByX(X)).thenReturn(Set.of(Optional.of(myObj)));

对于低版本的Java,还有很多其他的方法:

  1. 只需创建一个集合并添加一个元素
Set<Optional<MyClass>> set = new HashSet<>(); 
set.add(Optional.of(myObj));
Mockito.when(repository.findAllByX(X)).thenReturn(set);
  1. 使用Arrays.asList
Set<Optional<MyClass>> set = new HashSet<>(Arrays.asList(Optional.of(myObj));
Mockito.when(repository.findAllByX(X)).thenReturn(set);
  1. 使用匿名类
Set<Optional<MyClass>> set = new HashSet<String>(){{
    add(Optional.of(myObj));
}};
Mockito.when(repository.findAllByX(X)).thenReturn(set);
  1. 使用 Stream (Java 8+)
Set<Optional<MyClass>> set = Stream.of(Optional.of(myObj))
  .collect(Collectors.toCollection(HashSet::new));
Mockito.when(repository.findAllByX(X)).thenReturn(set);
  1. 使用第 3 方库

检查Google GuavaApache Commons CollectionsEclipse Collections 或您遇到的任何其他问题。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-09-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-06-02
    • 1970-01-01
    • 2022-12-18
    相关资源
    最近更新 更多