Skip to content
This repository has been archived by the owner on Mar 16, 2020. It is now read-only.

Latest commit

 

History

History
62 lines (50 loc) · 2.34 KB

mockable.md

File metadata and controls

62 lines (50 loc) · 2.34 KB

@mockable annotation

To use simply add "dev.zio" %% "zio-macros-test" % "<version>" to your libraryDependencies.

The @mockable annotation can be used on modules following the module pattern.

When applied to the module it will autogenerate the capability tags and the mockable implementation:

import zio.macros.annotation.mockable

@mockable
trait Example {
  val example: Example.Service[Any]
}

object Example {
  trait Service[R] {
    def foo()                 : ZIO[R, Nothing, Unit]
    def bar(v1: Int, v2: Int) : ZIO[R, Throwable, Int]
    def baz(v1: Int)(v2: Int) : ZIO[R, Nothing, String]
    def overloaded(v: Int)    : ZIO[R, Nothing, String]
    def overloaded(v: Long)   : ZIO[R, Nothing, String]
  }

  // -- below code is autogenerated -- //
  object foo extends zio.test.mock.Method[Example, Unit, Unit]
  object bar extends zio.test.mock.Method[Example, (Int, Int), Int]
  object baz extends zio.test.mock.Method[Example, (Int, Int), String]
  object overloaded {
    object _0 extends zio.test.mock.Method[Example, Int, String]
    object _1 extends zio.test.mock.Method[Example, Long, String]
  }

  implicit val mockable: zio.test.mock.Mockable[Example] = (mock: zio.test.mock.Mock) =>
    new Example {
      val example = new Service[Any] {
        def foo()                 : zio.IO[Nothing, Unit]   = mock(Example.foo)
        def bar(v1: Int, v2: Int) : zio.IO[Throwable, Int]  = mock(Example.bar, v1, v2)
        def baz(v1: Int)(v2: Int) : zio.IO[Nothing, String] = mock(Example.baz, v1, v2)
        def overloaded(v: Int)    : zio.IO[Nothing, String] = mock(Example.overloaded._0, v)
        def overloaded(v: Long)   : zio.IO[Nothing, String] = mock(Example.overloaded._1, v)
      }
    }
  // -- end of autogenerated code -- //
}

You can use the mockable implementation and capability tags to create ad-hoc mocked services like:

import zio.test.Assertion.equalTo
import zio.test.mock.Expectation.{ unit, value, valueF }

val mockEnv = (
  Example.foo returns unit *>
  Example.baz(equalTo(4 -> 2)) returns value("The answer to life:") *>
  Example.bar(equalTo(4 -> 2)) returns valueF { case (v1, v2) => s"$v1$v2" }
)

You will find more detailed information about the ZIO Mocking framework in howto section.