Easy Trait Testing in Scala
Scala has the notion of a trait, which is also sometimes referred to as a mixin. Traits are similar to interfaces in the Java world, but allow for partial implementations. This provides a convenient (and predictable) way of adding concrete implementations from a number of Traits to a single class. Say you have a simple trait such as:
trait Storage {
val storageName: String
require(storageName != null && storageName.nonEmpty)
def getStorageName = storageName
}
You’re writing a bunch of tests and would prefer not to instantiate an actual Storage class, instead you would rather test the trait itself. You can just do something like:
new {
val storageName = "Testing"
} with Storage {
assert(getStorageName != null)
assert(getStorageName nonEmpty)
assert(getStorageName equals "Testing")
}
The above code creates an anonymous class that fulfills the abstract requirements of Storage, and calls a few assertions to verify the implementation. There are some potential downsides to doing this type of instantiation but for quick tests it’s quite handy.
