Reputation: 1272
I am having troubles getting my first Mock working in my Chat application using Mockito, I am trying to mock a Repository that takes a user ID as a string and returns all the conversations for this user. I am having a very hard time getting rid of a NullPointerException
Here is my Repository trait:
trait UserRepository {
val getConversations: (String) => Option[Vector[User]]
}
Here is my Service:
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
}
}
And my tests
// 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")))
What I have tried so far:
Mock for UserRepository, hashCode: 1319190020
, but the UserService is not printing so it is the one throwing the NullPointerExceptionany[String]
, same error, and
anyString
same errorUpvotes: 2
Views: 2908
Reputation: 4296
Change your val
functions to def
functions.
Im not too sure exactly why this is, but mockito is a java library so im not surprised that it doesnt handle scala function values well where Def's compile to the same thing as java methods.
Upvotes: 2