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)
'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")
}
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).
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.