Last Updated: February 25, 2016
·
1.042K
· dgolubets

Scalamock mixed mock

Scalamock is the number one mocking library for Scala. It can create mocks in two ways:

  • with Scala macros
  • with Java proxies

Both methods aren't perfect and usually you want to use macro mocks with fallback to proxy sometimes.

Though library wasn't designed with this use case in mind, I found it easy to combine both mocks together.

import org.scalamock.scalatest.AbstractMockFactory
import org.scalamock.proxy.ProxyMockFactory
import org.scalatest.Suite
import scala.reflect.ClassTag

trait MixedMockFactory extends AbstractMockFactory {
  this: Suite =>

  object Proxy extends ProxyMockFactory {
    import org.scalamock.proxy._
    def mock[T: ClassTag]: T with Mock = super.mock[T]
    def stub[T: ClassTag]: T with Stub = super.stub[T]
  }
}

Use

class SomeSpec extends WordSpec with MixedMockFactory { 
  val macroMock = mock[Service1]
  val proxyMock = Proxy.mock[Service2]
}