微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

无法在 Kotlin 中使用 Optional 模拟 `willReturn`

如何解决无法在 Kotlin 中使用 Optional 模拟 `willReturn`

我有办法

fun getUser(userId: UserId): Optional<User?> = userRepository.findById(userId)

在 Java 中返回一个 Optional。 所以我想在我的 Kotlin 单元测试中模拟那个方法调用

这是我的第一个猜测...

given { mockedUserService.getUser(currentUser.userId) }.willReturn(Optional.of(currentUser))

...但是编译器说不

类型不匹配:推断的类型是可选的但可选的!预料之中

所以我开始制作 val currentUser: User? 只是为了让编译器满意。

given { currentUser?.userId?.let { mockedUserService.getUser(it) }.willReturn(Optional.of(currentUser))

类型不匹配:推断的类型是可选的但可选的?预料之中

类型不匹配:推断的类型是用户?但 TypeVariable(T) 是预期的

现在我有点迷失了。如何让编译器满意?

解决方法

将此视为替代方案。我假设您使用的是 Java 的类型 Optional 而不是您自己的实现(做的比我在这里看到的要多)。

Optional 来到 Java 是为了避免 NPE 并在运行时指示缺少类型。但是在 Kotlin 中,您实际上并不需要 Optional,因为您可以明确地将您的类型定义为可为空的 T?

因此您可以将其定义为:

fun getUser(userId: UserId): User?

fun getUser(userId: UserId): Optional<User> // not nullable!
,

您可以尝试 willAnswer 而不是 willReturn

x = 1:10;
y1 = 3*x;
y2 = x.^2;
ax(1) = subplot(2,1,1);
plot(x,y1,'b-')

ax(2) = subplot(2,2);
plot(x,y2,'r-*')
linkaxes(ax,'x')
,

一种方法是修复测试,但这实际上不是这里的问题。在 Kotlin 中,您应该尽可能避免 Optional。 Java 的类型系统无法区分可空值和不可空值。 Kotlin 可以,因此您应该尽早将 Optional<T> 转换为 T?

您可以像这样轻松修复您的功能:

fun getUser(userId: UserId): User? = userRepository.findById(userId).orElse(null)

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。