- Scala Design Patterns.
- Ivan Nikolov
- 165字
- 2021-08-27 19:09:56
Using a class
Let's have a look at how DoubledMultiplierIdentity, which we saw previously, would be tested. One would try to simply mix the trait into a test class and test the methods:
class DoubledMultiplierIdentityTest extends FlatSpec with ShouldMatchers with DoubledMultiplierIdentity
This, however, won't compile and will lead to the following error:
Error:(5, 79) illegal inheritance; superclass FlatSpec
is not a subclass of the superclass MultiplierIdentity
of the mixin trait DoubledMultiplierIdentity
class DoubledMultiplierIdentityTest extends FlatSpec with ShouldMatchers with DoubledMultiplierIdentity {
^
We already talked about this before and the fact that a trait can only be mixed in a class that has the same super class as itself. This means that in order to test the trait, we should create a dummy class inside our test class and then use it:
package com.ivan.nikolov.linearization
import org.scalatest.{ShouldMatchers, FlatSpec}
class DoubledMultiplierIdentityTest extends FlatSpec with ShouldMatchers {
class DoubledMultiplierIdentityClass extends DoubledMultiplierIdentity
val instance = new DoubledMultiplierIdentityClass
"identity" should "return 2 * 1" in {
instance.identity should equal(2)
}
}