我正在使用Scala 2.11。我可以使用Scala测试或Mockito模拟Scala类吗?我在StackOverflow和其他博客上看到的所有例子都是模仿scala的trait而不是类。我也尝试过使用JMockit,但它似乎不能与Scala一起工作。
使用scalatest和提供的MockitoSugar
模块,您可以执行以下操作(取自官方scalatest用户指南)
// 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")