paulbutcher / ScalaMock

Native Scala mocking framework
http://scalamock.org/
MIT License
502 stars 99 forks source link

How to mock method with by-name parameter #416

Closed andreisilviudragnea closed 2 years ago

andreisilviudragnea commented 2 years ago

If you want to discuss a new feature, please ignore/clear this form.

ScalaMock Version (e.g. 3.5.0)

3.5.0

Scala Version (e.g. 2.12)

2.13.6

Runtime (JVM or JS)

JVM

Reproducible Test Case

Please provide a minimised code snippet that fails, ideally, written as a failing test case in ScalaTest. This will help us a lot in diagnosing the problem and work on a fix. If the issue is more complex or requires configuration, please provide a link to a project on Github that reproduces the issue.

The following test runs and passes:

package org.example

import cats.effect.IO
import cats.effect.unsafe.implicits.global
import org.scalamock.scalatest.MockFactory
import org.scalatest.funsuite.AnyFunSuite
import org.scalatest.matchers.should

class ScalaMockSpec extends AnyFunSuite with should.Matchers with MockFactory {
  test("ScalaMock") {
    trait Logger {
      def info(message: => String): IO[Unit]
    }

    val logger = mock[Logger]

    (logger.info _: (=> String) => IO[Unit])
      .expects(*)
      .returning(IO.unit)

    Console.println(s"${logger.info("").unsafeRunSync()}")
  }
}

https://github.com/andreisilviudragnea/scala-playground/blob/main/src/test/scala/org/example/ScalaMockSpec.scala

How can I mock the logger.info call to expect a specific String as input (or any other matcher apart from *)?

I tried doing something like this:

  test("ScalaMock5") {
    trait Logger {
      def info(message: => String): IO[Unit]
    }

    val logger = mock[Logger]

    (logger.info(_: String))
      .expects("")
      .returning(IO.unit)

    Console.println(s"${logger.info("").unsafeRunSync()}")
  }

The test compiles, but fails because the mock is not set up properly.

andreisilviudragnea commented 2 years ago

@barkhorn Any help with this?

barkhorn commented 2 years ago

I suggest familiarizing yourself with this topic: https://scalamock.org/user-guide/matching/

I'll close this issue as this place is not for usage help. If you require a more detailed answer, you should try stackoverflow, or use the resources here https://scalamock.org/help/