1

In the following (simplified) example, how can I stub the value of a trait that inherits fields from a class with scalamock?

trait MyTrait extends MyClass
class MyClass(val location: Location)

val expectedValue = ???
val dor: MyTrait = stub[MyTrait]
(dor.location.continuousFeatureValues).returns(expectedValue)
Make42
  • 12,236
  • 24
  • 79
  • 155

2 Answers2

0

'location' is the parameter of MyClass or a data member of MyClass? Is it OK to change MyClass as:

class MyClass() {
  val location: Location = new Location
}

If it is OK, you can override the location as a workaround:

//source code
class Location {
  def continuousFeatureValues: String = "location"
}

class MyClass() {
  val location: Location = new Location
}

class MyTrait extends MyClass

// test code
it should "mock" in {
  val loc = mock[Location]
  val dor: MyTrait = new MyTrait {override val location = loc}
  (loc.continuousFeatureValues _).expects().returning("good")
  dor.location.continuousFeatureValues shouldBe ("good")
}
  • location is both a parameter of the constructor and a field member. I instantiate MyClass with it and later use it - similar to a case class, but it is not a case class. This solution seems to require quite a bit of changing my actual program and I don't like to do that for testing. – Make42 Oct 26 '16 at 11:08
0

I would refactor that code, as it is a bit of a dead end with a trait extending a class with a non-default constructor. If you were to mock that class directly, you still could not define actions on location as it is a val, and those are immutable in Scala. Make it a def on MyTrait and have MyClass extend MyTrait and your design should be simpler to work with (and mock).

Philipp
  • 967
  • 6
  • 16