Scala: Replacing a trait with a fake one for testing
We recently wanted to replace a trait mixed into one of our classes with a fake version to make it easier to test but forgot how exactly to do that!
The class is roughly like this:
trait Foo { def foo : String = "real foo" }
class Mark extends Foo {}
We originally tried to replace it like this:
trait BrokenFakeFoo { def foo : String = "broken fake foo" }
val m = new Mark with BrokenFakeFoo
error: overriding method foo in trait Foo of type => String;
method foo in trait BrokenFakeFoo of type => String needs `override' modifier
val m = new Mark with BrokenFakeFoo
If m compiled it would have two versions of foo but it wouldn’t know which one to use, hence the error message.
Attempt two was this:
trait BrokenFakeFoo { override def foo : String = "broken fake foo" }
error: method foo overrides nothing
trait BrokenFakeFoo { override def foo : String = "broken fake foo" }
As Uday pointed out, what we actually need to do is make our fake trait extend the original one and then override the method.
trait FakeFoo extends Foo { override def foo : String = "fake foo" }
val m = new Mark with FakeFoo
m.foo
> res5: String = fake foo
Since FakeFoo is the right most of the traits mixed into Mark its foo method will be used over the Foo one mixed into Mark on its class definition.
About the author
I'm currently working on short form content at ClickHouse. I publish short 5 minute videos showing how to solve data problems on YouTube @LearnDataWithMark. I previously worked on graph analytics at Neo4j, where I also co-authored the O'Reilly Graph Algorithms Book with Amy Hodler.