如何在Scala中模拟一个类

时间:2014-08-13 22:23:40

标签: scala mocking mockito jmockit

我正在使用Scala 2.11。我可以使用Scala测试或Mockito来模拟Scala类吗?我在StackOverflow和其他博客上看到的所有示例都是模拟scala Traits而不是类。此外,我尝试使用JMockit,它似乎不适用于Scala。

1 个答案:

答案 0 :(得分:2)

使用scalatest和提供的MockitoSugar模块,您可以执行以下操作(从official scalatest user guide获取)

// First, create the mock object
val mockCollaborator = mock[Collaborator]
// Create the class under test and pass the mock to it
classUnderTest = new ClassUnderTest
classUnderTest.addListener(mockCollaborator)

// Use the class under test
classUnderTest.addDocument("Document", new Array[Byte](0))
classUnderTest.addDocument("Document", new Array[Byte](0))
classUnderTest.addDocument("Document", new Array[Byte](0))
classUnderTest.addDocument("Document", new Array[Byte](0))

// Then verify the class under test used the mock object as expected
verify(mockCollaborator).documentAdded("Document")
verify(mockCollaborator, times(3)).documentChanged("Document")