简体   繁体   English

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

[英]Can't mock `willReturn` with Optional in Kotlin

I have a method我有一个方法

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

that returns an Optional in Java.在 Java 中返回一个 Optional。 So I want to mock that method call in my Kotlin unit test.所以我想在我的 Kotlin 单元测试中模拟该方法调用。

This was my first guess...这是我的第一个猜测...

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

... but the compiler says no ...但编译器说不

Type mismatch: inferred type is Optional but Optional<User?>!类型不匹配:推断类型是 Optional 但 Optional<User?>! was expected预计

So I started to make the val currentUser: User?所以我开始制作val currentUser: User? just to make the compiler happy.只是为了让编译器开心。

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

Type mismatch: inferred type is Optional but Optional<User?>?类型不匹配:推断类型是 Optional 但 Optional<User?>? was expected预计

Type mismatch: inferred type is User?类型不匹配:推断类型是用户? but TypeVariable(T) was expected但 TypeVariable(T) 是预期的

And now I am somewhat lost.现在我有点迷失了。 How can I make the compiler happy?我怎样才能让编译器满意?

Consider this as an alternative.将此视为替代方案。 I am assuming you are using Java's type Optional and not your own implementation (doing more than I can see here).我假设您使用的是 Java 的类型Optional而不是您自己的实现(比我在这里看到的更多)。

The Optional came to Java to avoid a NPE and indicate an abscent of a type at runtime. Optional来到 Java 以避免 NPE 并在运行时指示类型的缺失。 But in Kotlin you do not really need an Optional, since you can explicitely define your type as nullable T?但是在 Kotlin 中,您并不需要 Optional,因为您可以明确地将您的类型定义为可为空的T? . .

So you can either define it as:因此,您可以将其定义为:

fun getUser(userId: UserId): User?

or或者

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

You could try willAnswer instead of willReturn :您可以尝试willAnswer而不是willReturn

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

One way would be to fix the test, but that is actually not the problem here.一种方法是修复测试,但这实际上不是这里的问题。 You should avoid Optional whenever possible in Kotlin.您应该尽可能避免在 Kotlin 中使用Optional Java's type system has no way to distinguish nullable and non-nullable values. Java 的类型系统无法区分可空值和不可空值。 Kotlin does, so you should transform the Optional<T> as early as possible to T? Kotlin 可以,所以您应该尽早将Optional<T>转换为T? . .

You can easily fix your function like that:您可以像这样轻松修复 function:

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

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

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