我在使用Mockito的聊天应用程序中获得第一个模拟时遇到了困难,我试图模拟一个存储库,该存储库将用户ID作为字符串并返回该用户的所有对话。我很难摆脱NullPointerException
trait UserRepository {
val getConversations: (String) => Option[Vector[User]]
}
class UserService(userRepository: UserRepository){
private val boolToNumber : (Boolean) => Int = (bool) => ... not useful here
private val countToBool : (Int) => Boolean = (int) => ... not useful here
val getParticipations: (String) => Option[Vector[User]] = (name) => {
userRepository.getConversations(name) match {
... some implementation
}
}
// init
val userRepository = mock[UserRepository]
// setup
when(userRepository.getConversations("Smith")) thenReturn (
Some(
Vector(
User("Smith", true, true, ConversationKey("Smith", "Smith and O'Connell chatroom")),
User("Smith", false, true, ConversationKey("Smith", "Smith and O'Connell chatroom"))
)
)
)
val userService : UserService = new UserService(userRepository)
// run
val actual = userService.getParticipations("Smith")
// verify
actual mustBe Vector(User("Smith", false, true, ConversationKey("Smith", "Smith and O'Connell chatroom")))
到目前为止我所尝试的:
mock for UserRepository,hashcode:1319190020
,但是UserService没有打印,所以它是抛出NullPointerException的任意[String]
,相同错误,anystring
相同错误将val
函数更改为def
函数。
我不太确定这是为什么,但mockito是一个java库,所以我并不奇怪它不能很好地处理scala函数的值,而def的编译与java方法相同。