2011-04-11 52 views
4

我正在写Martining Fowler的Presentation Model模式之后的Swing应用程序。含有抽象val成员的嘲讽Scala特征

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

我如何可以模拟使用开源嘲讽框架(EasyMockMockito之一MainView性状的someLabel成员, JMockit等)进行单元测试?有没有另一个模拟框架,可能是特定于Scala,可以做到这一点?

回答

3

哈!在通勤家庭中发现它:-)。

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

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

3

其实,你不需要一些东西就可以嘲笑它def。根据斯卡拉的统一访问原则,defval几乎与外部相同。也就是说,对于val x,生成名为x()的获取方法,并生成名为x_=(newX)的设置器。

因此以下工作:

@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) 
}