How do I unit test closures with deeply nested anonymous functions in Scala?

421 views Asked by At

I'm trying to unit test a method that looks like this:

def foo() = {
  val a = Listener.registerCallback(
    (bar: Bar, baz: Baz) => {
      val x = bar.declare().get
      bar.bind(x)
  })
  return a
}

I can easily test the result of this method. My problem however is that when I run a coverage report (with sbt-coverage plugin and ScalaTest) I'm just a bit short of meeting my coverage threshold due to methods holding unreachable anonymous functions with local values as such.

Is there a way I can test this nested anonymous function to improve my coverage score?

1

There are 1 answers

0
Bill Venners On

Perhaps pull out out into a method that you test, then let eta expansion turn the method into a function? Something like:

def bippy(bar: Bar, baz: Baz) = {
  val x = bar.declare().get
  bar.bind(x)
}

def foo() = {
  val a = Listener.registerCallback(bippy)
  return a
}

I.e., now you could write a unit test against bippy and hopefully score points with sbt-coverage.