maks maks - 1 year ago 103
Scala Question

How to test stackable trait

Suppose I have such trait:

trait FooStackable {
def foo: String
def bar: Double

abstract override def logic(x: Double): Unit = {
if (x < 0) println(foo)
else super.logic(bar + x)
}
}


I want to write a test on the method
logic
for this trait in behaviour driven style: I want to check in test depending on input parameters what method was called and how many times. Apparently it's not possible simply to instantiate an instance of this trait(even when overriding unimplemeted methods), so mocks also will not work.

Does it make sense to write such test scenarios? (Real logic in method
logic
is more complex) And if yes how stackable traits are tested in isolation?

Answer Source

The code cannot be compiled as written. In particular, there is no 'super' in this trait as it is not derived from anything. I made some changes to work around it:

trait Stackable {
  def logic(x: Double): Unit
}

trait FooStackable extends Stackable {
  def foo: String
  def bar: Double

  abstract override def logic(x: Double): Unit = {
    println("In FooStackable.logic()")

   if (x < 0) println(foo)
    else super.logic(bar + x)
  }
}

trait TestStackable extends Stackable {
  def logic(x: Double): Unit = {
   println("In TestStackable.logic()")
  }
}

object FooStackableTest extends TestStackable with FooStackable {
  def foo: String = "foo"
  def bar: Double = 1.234

  override def logic(x: Double): Unit = {
   println("In FooStackableTest.logic()")

   super.logic(x)   
  }
}

With these changes FooStackable now sits in the middle between TestStackable (which implements logic() in a base class) and FooStackableTest (implements other undefined members of FooStackable and overrides logic()):

scala> FooStackableTest.logic(4.0)
In FooStackableTest.logic()
In FooStackable.logic()
In TestStackable.logic()

scala> FooStackableTest.logic(-4.0)
In FooStackableTest.logic()
In FooStackable.logic()
foo

scala> 
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download