2

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:

  • printing after each operation in the tests, printing UserRepository returns Mock for UserRepository, hashCode: 1319190020, but the UserService is not printing so it is the one throwing the NullPointerException
  • changing "Smith" by the matcher any[String], same error, and anyString same error
  • Wrapping String in a class called StringValue, same error Mockito matchers
3
  • 1
    Try changing your val functions to def functions.
    – Stephen
    May 28, 2017 at 13:41
  • 1
    That solved it!! Thank you, do you have any idea why it would cause a NullPointerException? EDIT: Can you answer (not with a comment) so I can accept your answer?
    – Daniel
    May 28, 2017 at 14:51
  • @Daniel, can you please update your example to add how you created test class and maven or sbt dependency. I cannot get how you mock with Mockito using the following syntax: val userRepository = mock[UserRepository].
    – Alexandr
    Jun 25, 2018 at 7:46

1 Answer 1

1

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.