【问题标题】:mocking method inside another method scala在另一个方法scala中模拟方法
【发布时间】:2019-06-15 16:39:21
【问题描述】:

我在模拟另一个方法中正在调用的方法时遇到问题。

例如:在我的主课下面。

class Trial extends TrialTrait {

  def run(): String ={
    val a = createA()
    val b = a.split(" ")
    val c = b.size
    val d = c + " words are there"
    d
  }

  def createA(): String = {
    var a = "above all the things that have been done, one thing remained in silent above all the things that have been done one thing remained in silent above all the that "
    a
  }
}

下面是我的模拟代码。

class TryMock4 extends FunSuite with BeforeAndAfterEach with MockFactory {

  val trial = new Trial
  val st = stub[TrialTrait]

  test("Mocking the DataFrame") {
    val input = "above all the things that have been done, one thing remained in silent above "
    (st.createA  _).when().returns(input)
    val expected = "14 words are there"
    val actual = st.run()
    Assert.assertEquals(expected,actual)
  }
}

我想要做的是将模拟数据传递给createA 并在run 方法中使用它。

但是,它在运行run 方法后给出了null 值。

您能否建议如何实现?

【问题讨论】:

  • 我不认为你可以用 ScalaMock 做到这一点。但是您可以使用Mockito 使用spy 来做到这一点。但实际上,您需要模拟一个内部方法来测试这一事实是一些错误设计的标志。所以我强烈建议首先考虑重构你的代码。
  • 感谢@SergGr 的回复。能否请您告诉我如何使用 spy 使用 Mockito 来做到这一点。如果您能提供示例代码,我将不胜感激。
  • Aswanikumar 你读过我链接的文档(第二个链接)吗?你试过吗? spy 的问题到底出在哪里?

标签: scala scalatest scalamock


【解决方案1】:

我认为在这种情况下您不需要模拟,只需常规覆盖就足够了。

class TrialTest extends FlatSpec with Matchers {
  behavior of "Trial"

  it should "count words" in {
    val input = "above all the things that have been done, one thing remained in silent above "

    val trial = new Trial {
      override def createA(): String = input
    }

    val expected = "14 words are there"
    val actual = trial.run()
    actual should be (expected)
  }
}

但是,如果您真的想在这里使用模拟,可以使用 scalamock。 您可以定义我们自己的类,使其成为最终类的一部分(您不想模拟的部分),见下文:

class TrialTestWithMock extends FlatSpec with Matchers with MockFactory {
  behavior of "Trial"

  it should "count words" in {
    val input = "above all the things that have been done, one thing remained in silent above "

    class FinalTrial extends Trial {
      final override def run(): String = super.run()
    }

    val trial = mock[FinalTrial]

    (trial.createA _).expects().returning(input).anyNumberOfTimes()
    val expected = "14 words are there"
    val actual = trial.run()
    actual should be (expected)
  }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多