scalafunctional-programmingscala-catsfor-comprehensionreader-monad

For comprehension not composing steps fully in unit test using Reader


I have a tagless final implementation with unit test, when I run the unit test only the first step is invoked not the rest.

Here is the test target:

class NameThing[F[_]: Monad](implicit console: Console[F]) {

  def program: F[Unit] = for {
    _ <- console.prompt
    rawName <- console.read
    fullName = parse(rawName)
    _ <- console.display(fullName)
  } yield ()

  def parse(rawName:String):FullName = {
    val parts = rawName.split(" ")
    FullName(parts(0), parts(1))
  }
}

The unit test is:

implicit object TestConsole extends Console[Test] {
      override def prompt: Test[Unit] = {
        println("ok1")
        Reader(TestEnv => TestEnv.prompt)
      }
      override def read: Test[String] =  {
        println("ok2")
        Reader(TestEnv => TestEnv.read)
      }
      override def display(fullName: FullName): Test[Unit] = {
        println("ok3")
        Reader(TestEnv => TestEnv.display(fullName.toString))
      }
    }

    val result = new NameThing[Test]().program.run

I only see ok1 displayed.

Complete code here: https://bitbucket.org/jameskingconsulting/scala-effects


Solution

  • Try

    new NameThing[Test]().program.run(TestEnv())
    

    new NameThing[Test]().program.run is just a TestEnv => Unit (where .run is Kleisli's run), you should call it on a TestEnv to actually run the program.