【问题标题】:How to call real method on a stub如何在存根上调用真实方法
【发布时间】:2020-02-07 12:11:12
【问题描述】:

有没有办法使用 scalamock 调用存根对象上的真实方法?

我希望能够做这样的事情:

class MySpec extends FunSpec with Matchers with MockFactory {
  trait MyTrait {
    def f1: Int
    def f2: Int = f1
  }

  describe("my feature") {
    it("should work") {
      val t = stub[MyTrait]
      (t.f1 _).when().returns(15)
      // I would like to do the following:
      // (t.f2 _).when().callRealMethod()
      t.f2 should be (15)
    }
  }
}

注意:我可以通过将 f2 设为 final 来解决此问题,但我想知道是否有办法在不更改被测代码的情况下解决此问题。

【问题讨论】:

    标签: scala scalamock


    【解决方案1】:

    我可以推荐的模式是按照您的建议将您不想模拟的函数设为最终的。但不是在实际代码中执行此操作,而是使用仅用于测试目的的子类,例如像这样:

    import org.scalamock.scalatest.MockFactory
    import org.scalatest.FunSuite
    import PartialMockingTest._
    
    class PartialMockingTest extends FunSuite with MockFactory {
    
      test("test case") {
    
        class PartFinalCls extends Cls {
          override final def B(): Int = super.B()
        }
    
        val f = stub[PartFinalCls]
        f.A _ when 7 returns 5
        assert(f.B() == 6)
      }
    
    }
    
    object PartialMockingTest {
      class Cls {
        def A(dummy: Int): Int = 5
    
        def B(): Int = A(7) + 1
      }
    }
    

    【讨论】:

      【解决方案2】:

      很遗憾,无法进行间谍活动: https://github.com/paulbutcher/ScalaMock/issues/249

      【讨论】:

        【解决方案3】:

        不幸的是,ScalaMock 不提供 «callRealMethod» 功能。

        如果可以更改测试框架,您可以使用 mockito-scalaMockitoSugar 特征来提供您想要的替代方法。

        你的代码看起来像这样:

        class MySpec extends FunSpec with MockitoSugar with Matchers {
        
          trait MyTrait {
            def f1: String = "mock"
        
            def f2: String = "not a mock"
          }
        
        
          describe("my feature") {
            it("should work") {
              val t = mock[MyTrait]
              when(t.f1).thenReturn("mocked")
              t.f1 shouldBe "mocked"
              when(t.f2) thenCallRealMethod()
              t.f2 shouldBe "not a mock"
            }
          }
        

        您需要添加 mockito scala 作为依赖项。 (sbt方式)

         "org.mockito" %% "mockito-scala" % "${version}",
         "org.mockito" %% "mockito-scala-scalatest" % "${version}"
        

        【讨论】:

        • 是的,我以前用 mockito 来做,这就是为什么我很惊讶没有在 scalamock 中找到它。
        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-08-18
        • 2011-07-15
        • 2021-11-28
        • 2010-12-20
        • 2020-05-23
        • 1970-01-01
        相关资源
        最近更新 更多