【发布时间】:2017-05-29 06:58:38
【问题描述】:
我在使用 Mockito 让我的第一个 Mock 在我的聊天应用程序中工作时遇到了麻烦,我正在尝试模拟一个将用户 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")))
到目前为止我所尝试的:
- 在测试中的每个操作后打印,打印 UserRepository 返回
Mock for UserRepository, hashCode: 1319190020,但 UserService 没有打印,所以它是抛出 NullPointerException 的那个 - 通过匹配器
any[String]更改“Smith”,同样的错误,并且anyString同样的错误 - 在名为 StringValue 的类中包装字符串,同样的错误 Mockito matchers
【问题讨论】:
-
尝试将您的 val 函数更改为 def 函数。
-
解决了!!谢谢,您知道为什么会导致 NullPointerException 吗?编辑:你能回答(不是评论),所以我可以接受你的回答吗?
-
@Daniel,您能否更新您的示例以添加您创建测试类和 maven 或 sbt 依赖项的方式。我无法使用以下语法使用 Mockito 进行模拟:val userRepository = mock[UserRepository].