Reputation: 667
I am using Scala 2.11. can I use Scala test or Mockito to mock Scala Classes? All the examples that I see on StackOverflow and other blogs are mocking scala Traits rather than classes. Also I tried to use JMockit and it does not seem to work with Scala.
Upvotes: 1
Views: 3042
Reputation: 108169
Using scalatest and the provided MockitoSugar
module, you can do something like this (take from the 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")
Upvotes: 2