dimanche 11 mars 2018

How to break down an object functionality in a test in Scala

This a generic question for a common problem, let's describe it as easy as I can... Suppose I have:

class A {
  def x() = //do something with e
  def e() = //do something else
}

basically a simple class where method x() is calling method e(). The logic of x() and e() are pretty complex. So it's not practical to test them in integration (by calling x() and asserting). It's easier to test x() and e() separately, with some mocking. So I could go and do:

abstract class A {
  def x() = {
    /* do */
  }

  def e()
}

object A {
  def eImpl() = {}

  def apply(): A = new A() {
    override def e(): Unit = eImpl()
  }
}

and then test the behaviour of x() with:

class ASpec extends FlatSpec {

  def eImpl() = {}

  def mockedA(inner: A => Unit) = {
    inner(new A {
      override def e(): Unit = ??? //some behaviour to help test, a mock, etc..
    })
  }

  "x in A" should "do this an that" in mockedA { a =>

  }

  "eImpl" should "do something else" in {

  }
}

but... This assumes that A() in the companion object binds the right implementation. And all in all it all seems a bit verbose to me maybe. So what could be a way to structure this class to be tested reliably and make sure that the instances have the right implementations?

Aucun commentaire:

Enregistrer un commentaire