question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

Mockito with Scala does not mock "val" functions

See original GitHub issue

I am using Mockito, ("org.mockito" % "mockito-core" % "1.8.5") in my Scala (version 2.11.11)-tests (Play Framework project)

Mocking a trait would always throw a JavaNullPointerException, the error was not helpful so I tried a several different things before someone suggested I try to change my val functions to def methods. (see my stack overflow question https://stackoverflow.com/q/44227298/4884034)

That solved it!

The error message should be more specific?

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 Some(Vector(User("Smith", false, true, ConversationKey("Smith", "Smith and O'Connell chatroom"))))

Issue Analytics

  • State:open
  • Created 6 years ago
  • Comments:11 (6 by maintainers)

github_iconTop GitHub Comments

1reaction
bbonannocommented, Apr 10, 2021

@ThibaultUrien you are correct, if what you store in the val is a function (or any other object with behaviuor), and said object also needs to be mocked for whatever reason, then you need 2 mocks, one for MyTrait and, in this case, one for the function.

So you’d end up with something like

    val mt          = mock[MyTrait]
    val strProvider = mock[Int => String]
    mt.stringProvider returns strProvider

    strProvider(*) returns "bob"

    println(mt.stringProvider(3))

A shorter way to write this could be achieved using deep stubs

    val mt = mock[MyTrait](DefaultAnswers.ReturnsDeepStubs)
    mt.stringProvider(*) returns "bob"

    println(mt.stringProvider(3))

Those 2 snippets of code are semantically equivalent, the difference is that DeepStubs will create all the intermediate mocks for you, so you can save yourself some boilerplate, the downside of course is that you lose the SmartNulls behaviuor, so it’s up to you which flavour you prefer.

1reaction
bbonannocommented, Jun 25, 2018

@djole103 I just tried this code

object MyClass extends App {

  import org.mockito.Mockito._

  trait MyTrait {
    val DefaultString = "myDefaultString"
    val DefaultInt = 42
  }

  val mt = mock(classOf[MyTrait])

  when(mt.DefaultString) thenReturn "Hi"
  when(mt.DefaultInt) thenReturn 7

  def printDefaults = {
    println(mt.DefaultString)
    println(mt.DefaultInt)
  }

  printDefaults
}

and it works as expected

this is what I put in my build.sbt

scalaVersion := "2.11.11"

libraryDependencies += "org.scalatest" %% "scalatest" % "3.0.5" % Test
libraryDependencies += "org.mockito" % "mockito-core" % "1.9.5" % Test

Is there anything else that you’re doing that could be different from my setup?

Read more comments on GitHub >

github_iconTop Results From Across the Web

How to mock a val initialized by a function in an object in Scala?
org.mockito.internal.util.reflection.Whitebox seems to work just fine. Since you tagged the question with mockito I assume you already have ...
Read more >
Using ScalaTest With Mockito | Baeldung on Scala
Mocking a No-Argument Method. Whenever the method getAll from the Dao is invoked, Mockito will return the predefined value, txns. We can use ......
Read more >
Mockito
Mockito allows to specify stubbed values and to verify that some calls have been made to your objects. In order to use those...
Read more >
Testing with mock objects - ScalaTest
ScalaMock is a native, open-source Scala mocking framework written by Paul Butcher that allows you to mock objects and functions. ScalaMock supports three ......
Read more >
User Guide - Choosing your mocking style - ScalaMock
If these expectations are not met, the test fails. Mocking functions. A mock function that supports this style is created with mockFunction ....
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found