Adam Pitt
Adam Pitt

Reputation: 128

ScalaMock Inheritied Trait Function of Object ScalaTest

I am attempting to test a function, however the function that I am testing makes a call to the traits function which I would like to stub. I can't seem to stub this function using ScalaMock, as I am unable to mock the object.

trait[A<:CommonReturn] commonTrait[A] {
    def commonFunction(s:String):(String,String) = {
        ("Hello","World")
    }
    def testMe(s:String) : A
}

This trait is then extended by many Objects each implementing commonTrait and returning their specific sub-type of common return.

object ob extends commonTrait[ConcreteType] {
    override def testMe(s:String){
        val(x,y) = commonFunction(s)
        val z = "unique logic"
        ConcreteType(x,y,z)
    }
}

I therefore am now trying to test ob.testMe however I can't seem to Mock the ob Object, therefore can't stub the commonFunction.

Is this due to my architecture? Or is it possible to mock an object with scalamock and use scalatest?

val mocked = mock[ob]
(mocked.commonFunction _).expect(*).returning("test","test")

This doesn't compile.

Upvotes: 0

Views: 382

Answers (1)

Philipp
Philipp

Reputation: 967

you cannot mock objects with ScalaMock, as a mock[X] is a subclass of X. Scala does not allow subclasses of objects.

If you need to test collaboration with this commonFunction then inheritance makes it rather difficult. I would consider designing this with Dependency Injection instead.

Upvotes: 0

Related Questions