Reputation: 7729
How would you compare Scala's object testability compare to testing statics in Java? Any pitfalls and traps?
Thank you.
Upvotes: 3
Views: 2949
Reputation: 2249
The same as statics in Java - references to objects are hard to swap for testing purposes, so you generally want to avoid them, except for side-effect-free, stateless utility methods, like Math.min, Math.max. Like in case of Java statics, objects holding state make testing particulary hard.
Scala objects have one advantage over the Java static, though - you can make your object extend some supertype and refer to through that interface. Then you can inject that object to the constructor of your client class, so your client gets more testable:
object MyRunnable extends Runnable {
def run() { }
}
class Client(r: Runnable) {
// ..
}
new Client(MyRunnable)
new Client(mock[Runnable]) // you can substitute the object with a mock for tests
With plain Java static, that is impossible. You can do similar thing with singletons in Java (to which Scala objects are similar).
Upvotes: 9
Reputation: 4580
In general, Scala singleton instances declared with the 'object' class are more amenable to testing than Java static methods, mostly because they're able to implement traits and extend other classes and so fit into the typical object-oriented testing paradigm.
Now, if you happen to do something unfortunate like store mutable state in a singleton object, you'll have the same sorts of problems that you end up with when testing Java singletons. Of course, there's an easy solution: never ever ever use 'var' in the body of an object. This is a trivial specialization of the superior advice of "never use var, period."
Upvotes: 3