模拟包含抽象 val 成员的 Scala 特征

2023-12-29

我正在按照 Martin Fowler 的思路编写 Swing 应用程序演示模型 http://martinfowler.com/eaaDev/PresentationModel.html图案。

我创建的特征包含已由 Swing 组件实现的方法的抽象声明:

trait LabelMethods {
  def setText(text: String)
  //...
}

trait MainView {
  val someLabel: LabelMethods
  def setVisible(visible: Boolean)
  // ...
}

class MainFrame extends JFrame with MainView {
  val someLabel = new JLabel with LabelMethods
  // ...
}

class MainPresenter(mainView: MainView) {
  //...
  mainView.someLabel.setText("Hello")
  mainView.setVisible(true)
}

我怎样才能嘲笑someLabel的成员MainView使用开源模拟框架之一的特征(EasyMock http://easymock.org/, Mockito http://mockito.org/, JMockit http://code.google.com/p/jmockit/等)进行单元测试?是否有另一个模拟框架(也许特定于 Scala)可以做到这一点?


哈!在回家的路上想通了:-)。

Scala 允许val在具体类中重写def在一个特质中。

我的特点变成:

trait LabelMethods {
  def setText(text: String)
  //...
}

trait MainView {
  def someLabel: LabelMethods    // Note that this member becomes
                                 // a def in this trait...
  def setVisible(visible: Boolean)
  // ...
}

My MainFrame类不需要改变:

class MainFrame extends JFrame with MainView {
  val someLabel = new JLabel with LabelMethods // ...But does not change
                                               // in the class
  // ...
}

我的测试用例代码如下所示:

class TestMainPresenter {
  @Test def testPresenter {
    val mockLabel = EasyMock.createMock(classOf[LabelMethods])

    val mockView = EasyMock.createMock(classOf[MainView])
    EasyMock.expect(mockView.someLabel).andReturn(mockLabel)
    //... rest of expectations for mockLabel and mockView

    val presenter = new MainPresenter(mockView)
    //...
  }
}

请注意,我还没有实际测试过这个,但它应该可以工作:-)。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

模拟包含抽象 val 成员的 Scala 特征 的相关文章

随机推荐