加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

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

发布时间:2020-12-16 18:10:50 所属栏目:安全 来源:网络整理
导读:我正在按照Martin Fowler的 Presentation Model模式编写一个Swing应用程序. 我创建的traits包含已由Swing组件实现的方法的抽象声明: trait LabelMethods { def setText(text: String) //...}trait MainView { val someLabel: LabelMethods def setVisible(v
我正在按照Martin Fowler的 Presentation Model模式编写一个Swing应用程序.

我创建的traits包含已由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)
}

如何使用开源模拟框架(EasyMock,Mockito,JMockit等)之一来模拟MainView特征的someLabel成员进行单元测试?是否有另一个模拟框架,也许特定于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)
  // ...
}

我的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)
    //...
  }
}

请注意,我实际上没有测试过这个,但它应该工作:-).

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读