1
+ /*
2
+ * Copyright 2001-2020 Artima, Inc.
3
+ *
4
+ * Licensed under the Apache License, Version 2.0 (the "License");
5
+ * you may not use this file except in compliance with the License.
6
+ * You may obtain a copy of the License at
7
+ *
8
+ * http://www.apache.org/licenses/LICENSE-2.0
9
+ *
10
+ * Unless required by applicable law or agreed to in writing, software
11
+ * distributed under the License is distributed on an "AS IS" BASIS,
12
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ * See the License for the specific language governing permissions and
14
+ * limitations under the License.
15
+ */
16
+ package org .scalatestplus .mockito
17
+
18
+ import org .scalatest .funsuite .AnyFunSuite
19
+ import org .mockito .Mockito .{verify , times }
20
+
21
+ class MockitoSugarSpec extends AnyFunSuite with MockitoSugar {
22
+
23
+ trait Collaborator {
24
+ def documentAdded (name : String ): Unit
25
+ def documentChanged (name : String ): Unit
26
+ }
27
+
28
+ class ClassUnderTest {
29
+
30
+ private val docs = new scala.collection.mutable.ListBuffer [String ]
31
+ private val listeners = new scala.collection.mutable.ListBuffer [Collaborator ]
32
+
33
+ def addListener (listener : Collaborator ): Unit = {
34
+ listeners += listener
35
+ }
36
+
37
+ def addDocument (name : String , bytes : Array [Byte ]): Unit = {
38
+ if (docs.contains(name))
39
+ listeners.foreach(_.documentChanged(name))
40
+ else {
41
+ docs += name
42
+ listeners.foreach(_.documentAdded(name))
43
+ }
44
+ }
45
+
46
+ }
47
+
48
+ test(" MockitoSugar should mock object for testing" ) {
49
+ // First, create the mock object
50
+ val mockCollaborator = mock[Collaborator ]
51
+
52
+ // Create the class under test and pass the mock to it
53
+ val classUnderTest = new ClassUnderTest
54
+ classUnderTest.addListener(mockCollaborator)
55
+
56
+ // Use the class under test
57
+ classUnderTest.addDocument(" Document" , new Array [Byte ](0 ))
58
+ classUnderTest.addDocument(" Document" , new Array [Byte ](0 ))
59
+ classUnderTest.addDocument(" Document" , new Array [Byte ](0 ))
60
+ classUnderTest.addDocument(" Document" , new Array [Byte ](0 ))
61
+
62
+ // Then verify the class under test used the mock object as expected
63
+ verify(mockCollaborator).documentAdded(" Document" )
64
+ verify(mockCollaborator, times(3 )).documentChanged(" Document" )
65
+ }
66
+
67
+ }
0 commit comments