Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/search/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
模拟包含抽象val成员的Scala特性_Scala_Mocking_Traits - Fatal编程技术网

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

模拟包含抽象val成员的Scala特性,scala,mocking,traits,Scala,Mocking,Traits,我正在按照Martin Fowler的模式编写一个Swing应用程序 我创建的特征包含Swing组件已经实现的方法的抽象声明: trait LabelMethods { def setText(text: String) //... } trait MainView { val someLabel: LabelMethods def setVisible(visible: Boolean) // ... } class MainFrame extends JFrame w

我正在按照Martin Fowler的模式编写一个Swing应用程序

我创建的特征包含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)
}

如何使用开源模拟框架(、等)模拟
MainView
trait的
someLabel
成员进行单元测试?是否有另一个模拟框架,可能是Scala特有的,可以做到这一点?

哈哈!在上下班回家的路上弄明白了:-)

Scala允许具体类中的
val
重写trait中的
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)
  // ...
}
我的
大型机
类不需要更改:

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

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

实际上,您不需要什么东西成为
def
就可以模拟它。根据Scala的统一访问原则,
def
val
从外部看几乎是相同的。也就是说,对于
valx
将生成名为
x()
的getter方法,并生成名为
x_=(newX)
的setter

因此,以下工作:

@Test
def testUap() {
  abstract class A {
    val x: Int
  }
  val mock = Mockito mock classOf[A]
  Mockito when (mock.x) thenReturn 5
  Assert.assertEquals(5, mock.x)
}