0

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

例如:在我的主课下面。

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方法中使用它。

但是,它null在运行该run方法后会产生价值。

您能否建议如何实现?

4

1 回答 1

0

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

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)
  }
}
于 2019-01-23T21:08:43.083 回答