Mocking Scala trait containing abstract val elements

I am writing a Swing application after the Martin Fowler Model Presentation Model .

I create traits containing 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) } 

How can I mock someLabel element of someLabel attribute using one of the open source camera angles ( EasyMock , Mockito , JMockit , etc.) for unit testing? Is there any other mocking structure, possibly Scala specific, that can do this?

+4
source share
2 answers

Huh! It turned out that in the switched house :-).

Scala allows val in a particular class to override def in a tag.

My traits are becoming:

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

I do not need to change the MainFrame class:

 class MainFrame extends JFrame with MainView { val someLabel = new JLabel with LabelMethods // ...But does not change // in the class // ... } 

My test code is as follows:

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

Please note that I have not actually tested this, but it should work :-).

+3
source

In fact, you don’t need to be def anything to be able to mock him. According to Scala's principle of uniform access, def and val almost identical from the outside. That is, for val x , a getter method with the name x() generated and a setter with the name x_=(newX) .

Thus, the following work:

 @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) } 
+3
source

Source: https://habr.com/ru/post/1347610/


All Articles