模拟包含抽象 val 成员的 Scala 特征
我正在按照 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)
}
How can I mock the someLabel
member of the MainView
Trait using one open-source mocking Framework (< a href="http://easymock.org/" rel="nofollow">EasyMock, Mockito 、JMockit 等)进行单元测试?是否有另一个模拟框架(也许特定于 Scala)可以做到这一点?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
哈!在回家的路上想通了:-)。
Scala 允许具体类中的 val 覆盖特征中的 def 。
我的特征变成:
我的
MainFrame
类不需要更改:我的测试用例代码如下所示:
请注意,我还没有实际测试过它,但它应该可以工作:-)。
Hah! Figured it out on the commute home :-).
Scala allows a
val
in a concrete class to override adef
in a trait.My traits become:
My
MainFrame
class does not need to change:My test case code looks like this:
Note that I have not actually tested this, but it should work :-).
实际上,您不需要将某个东西作为
def
来模拟它。根据Scala的统一访问原则,从外部看,def
和val
实际上是相同的。也就是说,对于val x
会生成名为x()
的 getter 方法,并生成名为x_=(newX)
的 setter。因此,以下工作:
Actually, you don't need something to be a
def
just to be able to mock it. According to Scala's Uniform Access Principle, thedef
andval
are virtually the same from the outside. That is, for aval x
a getter method namedx()
is generated, and a setter namedx_=(newX)
is generated.Thus the following works: