包含抽象val成员的模拟Scala特性 [英] Mocking Scala traits containing abstract val members
问题描述
我正在按照Martin Fowler的演示模型模式编写一个Swing应用程序.
I am writing a Swing application following Martin Fowler's Presentation Model pattern.
我创建的特征包含由Swing组件已经实现的方法的抽象声明:
I create traits that contain abstract declarations of methods already implemented by Swing components:
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 等)进行单元测试?是否有另一个模拟框架,也许特定于Scala可以做到这一点?
How can I mock the someLabel
member of the MainView
trait using one of open-source mocking frameworks (EasyMock, Mockito, JMockit, etc.) for unit testing? Is there another mocking framework, perhaps specific to Scala that can do this?
推荐答案
H!在通勤的家中找到了它:-).
Hah! Figured it out on the commute home :-).
Scala允许具体类中的val
覆盖特征中的def
.
Scala allows a val
in a concrete class to override a def
in a trait.
我的特质变成:
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
// ...
}
我的测试用例代码如下:
My test case code looks like this:
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)
//...
}
}
请注意,我尚未对此进行实际测试,但它应该可以工作:-).
Note that I have not actually tested this, but it should work :-).
这篇关于包含抽象val成员的模拟Scala特性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!