Mockito user’s manual

Zero:

One: Create mock/ Spy objects

Zero:

Mockito makes it easy to create objects under test, mock objects, and Spy objects.

  • Create the object under test:
    • First, explain the object under test: the class we want to test in a unit test. Such as xxxService, xxxUtils and so on.
    • Create with the @injectMocks annotation:
      • Cooperate with@RunWith(MockitoJUnitRunner.class)Use or in@BeforeMethod.MockitoAnnotations.openMocks(this)To enable Mockito annotations.
      • If you also use the @mock or @spy annotation. Mockito can easily inject the objects generated by these two annotations into the member variables of the @InjectMocks object.
    • Create directly:
      • Of course we can directly new an object under test, but we can not easily use the automatic injection of member variables provided by Mockito. Of course we can do this manually.
  • Create mock objects:
    • Mock objects: Typically objects that the object under test depends on (such as member variables of the object under test).
    • Use the @mock annotation:
      • Cooperate with@RunWith(MockitoJUnitRunner.class)Use or in@BeforeMethod.MockitoAnnotations.openMocks(this)To enable Mockito annotations.
      • Objects annotated by @mock are automatically injected into the objects under test generated by the @InjectMocks annotation.
    • Use Mockito. Mock ();
      • The generated mock object must be manually configured into the object under test and is not recommended.
    • Note:
      • By default, methods in mock objects return a null value for an object of the corresponding type when called. The actual code of the method is not executed. Currently we can execute the actual code if we want:
        • We can stub this method first, using either doCallRealMethod() or thenCallRealMethod(). Details on how to do this are described below.
        • This can also be done by specifying a return value policy (Mockito.CALLS_REAL_METHODS). That is, when creating mock objects, specify the return value policy as mockito.calls_real_methods.
      • By default, methods in mock objects return a null value for an object of the corresponding type when called. In many cases when we don’t stub a side the return value is null and NPE is generated during testing. But we can specify a return value generation strategy (Answer strategy) when we create mock objects. Details on how to do this are described below.
  • Create a Spy object:
    • Spy object: Objects of partial mocks. Usually objects that the object under test depends on (such as member variables of the object under test).
    • Use the @spy annotation:
      • Cooperate with@RunWith(MockitoJUnitRunner.class)Use or in@BeforeMethod.MockitoAnnotations.openMocks(this)To enable Mockito annotations.
      • Objects annotated by @Spy are automatically injected into the objects under test generated by the @InjectMocks annotation.
    • Use Mockito. Spy ();
      • The generated Spy object must be manually configured into the object under test and is not recommended.
    • Note:
      • Methods in a SPY object are called with the actual code of the method by defaultWill be performed. Now if we want toDoes not performThe actual code is also ok:
        • We can stub this method first, using the doXXXX() method (be careful not to use the or thenXXXX() method, which will cause us trouble: the actual code will be called once at this point). Details on how to do this are described below.

1: Create mock objects

  • Use the mockito.mock () method.

            //org.mockito.Mockito.mock(java.lang.Class<T>)
            //org.mockito.Mockito.mock(java.lang.Class<T>, java.lang.String)
            //org.mockito.Mockito.mock(java.lang.Class<T>, org.mockito.stubbing.Answer)
            //org.mockito.Mockito.mock(java.lang.Class<T>, org.mockito.MockSettings)
            
            1 / / way
            Foo foo1 = Mockito.mock(Foo.class);
            // Method 2: Name the mock
            Foo foo2 = Mockito.mock(Foo.class, "mock_1");
            // Approach 3: Specify custom return logic for the mock
            Foo foo3 = Mockito.mock(Foo.class, new Answer() {
                @Override
                public Object answer(InvocationOnMock invocation) throws Throwable {
                    // Customize the return logic
                    return null; }});// Approach 4: Use MockSettings to configure the current mock
            Foo foo4 = Mockito.mock(Foo.class, Mockito.withSettings().defaultAnswer(Mockito.RETURNS_SMART_NULLS));
    Copy the code
  • Use @injectMocks and @Mock annotations.

    • The object annotated by @injectMocks is the object to be tested, and it will be instantiated automatically. And it contains member variables that are automatically assigned by the corresponding @mock annotation object. Take a look at the following example:
    • Pay attention to use@RunWith(MockitoJUnitRunner.class)Annotation.
    public class Foo {
    
        private Bar bar;
    
        public int sum(int a, int b) {
            returnbar.add(a, b); }}Copy the code
    public class Bar {
    
        public int add(int a, int b) {
            returna + b; }}Copy the code
    // Note that we used MockitoJUnitRunner
    @RunWith(MockitoJUnitRunner.class)
    public class MockitoTest {
      	// Member variables inside foo are automatically injected into objects generated by the @mock annotation.
        @InjectMocks
        private Foo foo;
    
      	// The bar object is automatically injected into the @injectMocks object's member variables.
        @Mock
        private Bar bar;
    
        @Test
        public void mockTest(a) {
          	// Stub the mock object's method under test first when the mock object's method is actually executed
          	// Returns the stub's result without calling the actual code of the mock object
            Mockito.when(bar.add(1.2)).thenReturn(7);
            
          	int result = foo.sum(1.2);
          	// Verify that it is the value returned by the stub
            Assert.assertEquals(7, result); }}Copy the code
  • Matters needing attention:

    • By default, a mock will return NULL, raw/raw wrapper value, or an empty collection for all method return values, depending on the case. For example, int/Integer returns 0 and Boolean/Boolean returns false. We can change this return by specifying the default Answer policy when we create the mock. Supported Answer policies:

      • Mockito.RETURNS_DEFAULTS;
        • This implementation first tries global configuration, and if there is no global configuration, it uses a default Answer that returns 0, empty set, empty value, and so on.
      • Mockito.RETURNS_DEEP_STUBS;
        • Chain calls avoid null Pointers.
      • Mockito.RETURNS_MOCKS;
        • First try returning normal values (0, empty collection, empty string, etc.) and then try returning a mock. If the return type cannot be mocked (for example, final), plain NULL is returned.
      • Mockito.RETURNS_SELF;
        • Allows a mock of the Builder to return itself when calling a method that returns Type equal to the class or superclass. Remember that this Answer uses the return type of the method. If this type can be assigned to a mock class, it returns a mock. So, if you have a method that returns a superclass (Object, for example), it will match and return the mock.
      • Mockito.RETURNS_SMART_NULLS;
        • This implementation is helpful when dealing with legacy code. Non-stub methods usually return NULL. If your code uses a non-stub call to the returned object, you get a NullPointerException. This implementation of Answer returns SmartNull instead of NULL. SmartNull gives a better exception message than NPE because it indicates the line where the stubble-free method was called. You simply click on the stack to trace. SmartNull first tries to return normal values (0, empty collection, empty string, etc.) and then tries to return SmartNull. If the return type is final, pure NULL is returned. In Mockito 4.0.0, ReturnsSmartNulls might be the default return value policy.
      • Mockito.CALLS_REAL_METHODS
        • An Answer that calls the actual method (for part of the mock).

2: Create a Spy object

  • Use the mockito.spy () method

        {
            //org.mockito.Mockito.spy(java.lang.Class<T>)
            //org.mockito.Mockito.spy(T)
    
            // Approach 1: spy a specific type
            List spy1 = Mockito.spy(List.class);
            // Approach 2: spy an existing object
            List spy2 = Mockito.spy(new ArrayList<>());
    
            // Handy API, new overloaded spy() method:
            SomeAbstract spy = spy(SomeAbstract.class);
    
            Mocking abstraction, the default spy interface method (available from 2.7.13)
            Function function = spy(Function.class);
    
            // Robust API from Settings Builder:
            OtherAbstract spy = mock(OtherAbstract.class, withSettings()
                .useConstructor().defaultAnswer(CALLS_REAL_METHODS));
    
            //Mock an abstract class that uses constructors (available from 2.7.14)
            SomeAbstract spy = mock(SomeAbstract.class, withSettings()
                .useConstructor("arg1".123).defaultAnswer(CALLS_REAL_METHODS));
    
            //mock a non-static inner abstract classInnerAbstract spy = mock(InnerAbstract.class,withSettings().useConstructor().outerInstance(outerInstance).defaultAnswer(CALLS_REAL_METHODS)) ; }Copy the code
  • Use the @spy annotation.

    • The objects annotated by @injectMocks are generally the objects we are testing. It will be instantiated automatically. And it contains member variables that are automatically assigned by the corresponding @spy annotated object. Take a look at the following example:
    • Pay attention to use@RunWith(MockitoJUnitRunner.class)Annotation.
    // Note that we used MockitoJUnitRunner
    @RunWith(MockitoJUnitRunner.class)
    public class MockitoTest {
        @InjectMocks
        private Foo foo;
    
        @Spy
        private Bar bar;
    
        // You can do that
        @Spy
        private Bar bar2 = new Bar();
    
        @Test
        public void mockTest(a) {
            // stub the add method on the SPY object
            Mockito.when(bar.add(1.2)).thenReturn(7);
            
          	int result = foo.sum(1.2);
            Assert.assertEquals(7, result);
        }
    
        @Test
        public void mockTest2(a) {
            // Without the SPY object stub, the actual method is called.
            // Note the difference with a mock object: a mock object defaults to a null value of the return type. The Spy object executes the actual method and returns by default.
            int result = foo.sum(1.2);
            Assert.assertEquals(3, result); }}Copy the code
  • Matters needing attention:

    • Differences from mock objects:

      • The mock object’s default return type is null (return policies can be configured) and does not execute the actual method.
      • The Spy object executes the actual method and returns by default, and you can stub a method of the Spy object to specify the return value and avoid calling the actual logic of the method.
    • Sometimes it is impossible or impractical to use when(Object) for stubbed SPY objects. So please consider when using spy use doReturn | Answer | Throw () stub methods. Example:

         List list = new LinkedList();
         List spy = spy(list);
      
         // The following code is not possible: the actual code for the spy.get(0) method will be called and will be thrown
      	 / / IndexOutOfBoundsException (the list is still empty).
         // Why is the actual code of the method called when the stub is used? Wouldn't that make it impossible to stub this method?
         // When (spy.get(0)) is spy.get(0);
         // Spy.get (0) has not yet been stubbed. So the actual code for this method is called. To solve this problem,
         // Use the doXXX() method with when() for stubbing.
         when(spy.get(0)).thenReturn("foo");
      
         // You need to use doReturn() to remove stubs
         doReturn("foo").when(spy).get(0);
       
      Copy the code
    • Mockito does not pass the call to a real instance, but actually creates a copy of it. Therefore, if you keep real instances and interact with them, you should not expect the person being monitored to know about those interactions and their impact on the state of the real instance. Correspondingly, when the unstubbed (no stub) method is called on the SPY object but not on the real instance, you will not see any impact on the real instance.

      • This means that the SPY object is actually a copy of the real object; Calls to methods in spy do not affect real objects.
    • Note the final method. Mockito does not mock final methods, so the bottom line is: when you monitor real objects (using the Spy () method) + try stubbing final methods = trouble. You will also not be able to validate these methods.

3: Creates a measured object

  • Use @injectMocks annotations. (need to cooperate with @ RunWith (MockitoJUnitRunner. Class) use or use in @ Before method MockitoAnnotations. OpenMocks (this) to activate Mockito annotation of related functions.)

    {
        @InjectMocks
        private Foo foo;
    
        @Mock
        private Bar bar; 
      
    }
    Copy the code
    • Description: The object under testfooIf containsBarType, at which point Mockito will automaticallybarInjected into thefooIn the@InjectMocksObject of annotationfooIts actual code logic is executed when its methods are called. by@MockObject of annotationbarInstead of executing the actual code logic, the method in.
    {
        @InjectMocks
        private Foo foo;
    
        @Spy
        private Bar bar = new Bar();
    
    }
    Copy the code
    • Explanation: Different from the abovebarThe object is aspyObject. By default, whenbarObject when a method is called, the actual code is executed. Of course you can. Yeah.barObject to specify the return value of this method without calling its actual method. Note that stubs are the way to use themdoXXXX(x).when(spy).m1()Rather thanwhen(spy.m1()).thenReturn(x)The way; The latter calls the actual code logic of the method once during the stub procedure.
  • Matters needing attention:

    • What @injectMocks does: Mark fields that should be injected (meaning fields in this object should be injected automatically with values from fields in the @mock or @spy annotation).

      • Allows for fast mock and Spy injection.
      • Minimize duplicate mock and Spy injection code.

      Mockito will attempt to inject Mock objects only through constructor injection, setter injection, or property injection, as described below. Mockito does not report failure if any of the following policies fail; That is, you must provide your own dependencies.

      1. Constructor injection: Select the largest constructor (with the most method parameters), and then parse the parameters using a mock declared only in the test class. If the object is successfully created using the constructor, no other strategy is tried. Mockito decided not to destroy objects with parameter constructors.

        Note: If no argument is found, null is passed. If non-mock types are required, constructor injection will not occur. In these cases, you must satisfy the dependencies yourself.

      2. Property setter injection (setter method) : Mockito will first resolve by type (injection will occur regardless of the name if a single type matches), and then, if there are multiple properties of the same type, it will be injected by matching the property name and mock name.

        Note 1: If you have attributes of the same type (or the same type erased), it is best to name all @Mock annotation fields with matching attributes, otherwise Mockito may cause confusion and will not inject.

        Note 2: If the @InjectMocks object has not been initialized before and has a no-argument constructor, it will be initialized with that constructor.

      3. Field injection: Mockito will first resolve by type (injection will occur regardless of the name if a single type matches) and then, if there are multiple properties of the same type, inject by matching the field name and the mock object name.

        Note 1: If you have fields of the same type (or the same type erased), it is best to name all @mock annotations’ fields with matching fields, otherwise Mockito may be open to libation and uninjected.

        Note 2: If the @InjectMocks object has not been initialized before and has a no-argument constructor, it will be initialized with that constructor.

      Example:

      public class ArticleManagerTest extends SampleBaseTestCase {
      
          @Mock
          private ArticleCalculator calculator;
          
          @Mock(name = "database")
          private ArticleDatabase dbMock; // note the mock name attribute
          
          @Spy
          private UserProvider userProvider = new ConsumerUserProvider();
      
          @InjectMocks
          private ArticleManager manager;
      
          @Test
          public void shouldDoSomething(a) { manager.initiateArticle(); verify(database).addListener(any(ArticleListener.class)); }}public class SampleBaseTestCase {
      
          private AutoCloseable closeable;
      
          @Before
          public void openMocks(a) {
              closeable = MockitoAnnotations.openMocks(this);
          }
      
          @After
          public void releaseMocks(a) throws Exception { closeable.close(); }}Copy the code

      In the example above, the @InjectMocks annotation’s field ArticleManager can have only one parameterized constructor or one parameterless constructor, or both. The visibility of all of these constructors can be package-Protect, protected, or private, but Mockito cannot instantiate inner classes, native classes, abstract classes, and of course interfaces. Also be aware of private nested static classes.

      Also setters or fields, their visibility declarations can be private, and Mockito will see them through reflection. However, static or final fields are ignored.

      So in areas where injection is needed, such as constructor injection occurs here:

         public class ArticleManager {
             ArticleManager(ArticleCalculator calculator, ArticleDatabase database) {
                 // parameterized constructor}}Copy the code

      The property setter injection will occur here:

         public class ArticleManager {
             // no-arg constructor
             ArticleManager() {  }
      
             // setter
             void setDatabase(ArticleDatabase database) {}// setter
             void setCalculator(ArticleCalculator calculator) {}}Copy the code

      Field injection will be used here:

         public class ArticleManager {
             private ArticleDatabase database;
             private ArticleCalculator calculator;
         }
       
      Copy the code

      Finally, in this case, injection does not occur:

         public class ArticleManager {
             private ArticleDatabase database;
             private ArticleCalculator calculator;
      
             ArticleManager(ArticleObserver observer, boolean flag) {
                 // observer is not declared in the test above.
                 // flag is not mockable anyway}}Copy the code

      Note again that @injectmocks will only InjectMocks /spies objects created using @spy or @mock annotations.

      You must call * * MockitoAnnotations. OpenMocks (this) * * method to initialize the annotated object. In the example above, openMocks() is called in the @before (JUnit4) method of the test base class. For JUnit3, openMocks() can go to the setup() method of the base class. ** Instead, ** You can also put openMocks() in the JUnit runner (@runwith) or use the built-in MockitoJUnitRunner. Also, be sure to release any mocks after processing the test class with the appropriate hooks.

      Mockito is not a dependency injection framework, so don’t expect this quick utility to inject complex object diagrams, whether mocks/ Spies or real objects.

4: reference

  • Mockito official documentation:
    • 9. Simple mocks creation method –@Mock annotations
    • 16. Real Partial Mocks (since 1.8.0)
    • 21. New notes: @captor, @Spy, @InjectMocks (since 1.8.3)
    • 23. Automatically instantiate objects using @spies, @InjectMocks with good constructor injection (after 1.9.0)
    • 30. Monitor or Mock abstract classes (since 1.10.12, further enhanced in 2.7.13 and 2.7.14)
    • 32. Better general support for deep stubs (since 1.10.0)
    • Mockito JUnit Rule (from 1.10.17)
    • 37.Java 8 Custom Answer support (since 2.1.0)
    • 38. Retention of metadata and generic types (since 2.1.0)
    • 39. Mock Final classes, enumerations, and final methods (since 2.1.0)
    • 48. Mock static methods (since 3.4.0)
    • 49. Mock object constructs (since 3.5.0)

5: Common problems

  1. What is the difference between mock objects and Spy objects?
    1. The mock object’s default return type is null (return strategy can be configured), and its methods are called without executing the actual code logic and instead return directly.
    2. The Spy object executes the actual method logic by default and returns, and you can stub a method of the Spy object to specify the return value and avoid calling the actual method logic.
  2. What are the return value policies for mock objects? How to configure it?
    1. Please refer to the above introduction.
  3. Are there any special requirements for stubbing a method of a Spy object? Why do I sometimes get the actual logic of the method called even though I’m doing a stub operation?
    1. Stub requirement: use doXXX(x).when(spy).m1() instead of whenXXX(spy.m1()).thenxxx (x).
    2. Why the actual logic is called: Because the whenXXX(spy.m1()).thenxxx (x) stubs are used. The details have been introduced above. Please refer to.
  4. What are the best practices for creating this set of test-related objects?
    1. Using the @injectMocks annotation, Combination use of annotations on the class @ RunWith (MockitoJUnitRunner. Class) rather than using MockitoAnnotations in @ Before method. The openMocks (testClass) way of creating the object being measured. Our rule is to use annotations whenever possible to create test related objects.
    2. Create a Mock object using @mock instead of the mockito.mock () method.
    3. Create Spy objects using @spy instead of the mockito.spy () method. Use mockito.spy () if you find @spy does not easily meet your requirements in a specific test method.

Two: stub method calls

  • How to define stub methods:

    • Mockito.when(foo.sum()).thenXXX(…) ;

      • The stub for the foo.sum() method.
      • Note:
        • The Foo object should be a mock object. Stubbing spy objects in this way is not recommended. Because when(foo.sum()). The foo.sum() method is executed first. The actual code logic that causes the sum() method to be executed. Whether the actual code logic for (sum() is executed depends on the type of the spy object, not when the spy object is a mock object or interface – these types also have no actual code logic to execute. The actual code logic is executed when spy objects a concrete object)
    • Mockito.doXXX(…) .when(foo).sum();

      • The stub for the foo.sum() method.
      • You can stub the void method.
      • The Foo object can be a mock object or a Spy object.
    • Mockito.doXXX(….) .when(foo.sum());

      • You get an exception that should not be used this way!

      • org.mockito.exceptions.misusing.UnfinishedStubbingException: 
        Unfinished stubbing detected here:
        -> at c.FooTest.verifyTest(FooTest.java:23)
        
        E.g. thenReturn() may be missing.
        Examples of correct stubbing:
            when(mock.isOk()).thenReturn(true);
            when(mock.isOk()).thenThrow(exception);
            doThrow(exception).when(mock).someVoidMethod();
        Hints:
         1. missing thenReturn(a)
         2. you are trying to stub a final method, which is not supported
         3. you are stubbing the behaviour of another mock inside before 'thenReturn' instruction is completed
        Copy the code
  • How to define a return value:

    • Then_xxx method Do_XXX method function
      then(Answer<? > answer) doAnswer(Answer answer) Return value Uses the custom Answer policy.
      thenAnswer(Answer<? > answer) Same as above Same as above.
      thenReturn(T value) doReturn(Object toBeReturned) Specify the return value directly.
      thenReturn(T value, T… values) doReturn(Object toBeReturned, Object… toBeReturnedNext) Specify the return value directly. You can define multiple return values. The first call to the stub method returns the first return value. And so on. Calls that exceed the number of return values return the last return value of the argument.
      thenCallRealMethod() doCallRealMethod() Call the actual code logic. No return value is specified.
      thenThrow(Throwable… throwables) doThrow(Throwable… toBeThrown) Throws an exception when the stub method is called.
      Same as above doThrow(Class<? extends Throwable> toBeThrown) Throws an exception when the stub method is called. Multiple exceptions can be defined. The first call to the stub method returns the first exception. And so on. Calls that exceed the number of exceptions return the last exception of the argument.
      Same as above doThrow(Class<? extends Throwable> toBeThrown, Class<? extends Throwable>… toBeThrownNext) Same as above.
      No corresponding method doNothing() The stub mode used by the void method.
  • Parameter matching machine

    • Parameter matchers are typically used when calling stub methods.
    • Parameter matchers can also be used for method validation.
    • 3: Parameter matching
      • There is an introduction to parameter matchers
  • The sample

    • 2: Add some stubs: specify the return value of the mock object method call
      • Three considerations
    • 5. Stub has abnormal void method
    • 10. Continuous stubbing (iterator-style stubbing)
    • 11. Stub with callback
    • 12. DoReturn () | doThrow () | doAnswer () | doNothing () | doCallRealMethod () method
    • 13.Monitor real objects: Use SPY
      • Contains some tips for using Spy
    • 14. Change the default return value for unstub calls (since 1.7)
    • 16.Real part of the mock(Since 1.8.0)
      • Use Spy or mock.
      • ThenCallRealMethod () method.
  • Matters needing attention:

    • TODO

Three: Validate method calls

Verification method:

Whether a method is called/how many times a method is called

  • atLeast(int minNumberOfInvocations)Allow validation of at least X calls.
  • atLeastOnce()Allows validation of at least one invocation.
  • atMost(int maxNumberOfInvocations)Allows validation up to X calls.
  • atMostOnce()Validation for up to one invocation is allowed.
  • never() times(0)Alias, seetimes(int)
  • only()Allows you to check if a given method is called only once.
  • times(int wantedNumberOfInvocations)Allows you to verify the exact number of calls.
  • verify(T mock)Validate some behaviorIt happened once.
  • verify(T mock, VerificationMode mode)Verify that some behavior occurred at least once/exactly how many times/never occurred.
  • verifyNoInteractions(Object... mocks)Verify that no interaction occurs on a given simulation.
  • verifyNoMoreInteractions(Object... mocks)Checks for any unvalidated interactions with any given simulation.

Method execution time

  • after(long millis)Validation is triggered after a given number of milliseconds, allowing testing of asynchronous code.
  • timeout(long millis)Validation is triggered over and over again, up to a given number of milliseconds, allowing testing of asynchronous code.

Call order validation

  • calls(int wantedNumberOfInvocations)Allows sequential validation of non-greedy calls.
  • inOrder(Object... mocks)createInOrderObject that allows you to mock out in sequence.

Example:

  • 1: Verify the mock object’s behavior (whether the method is called and the value returned from the call)
  • 4: Verify the exact number of calls/at least x calls/never calls
  • 6: Call order verification
  • 7. Make sure there is no interaction on the mock object
  • 8. Look for extra calls
  • 15. For further assertionCapture parameters(Since 1.8.0)
    • Some warnings about capturing parameters for assertion.
  • 22. Timeout validation (since 1.8.5)
  • 35. Custom validation failure messages (since 2.1.0)
  • 40. Use “tougher” Mockito to increase productivity and write simpler tests (since 2.+)

Verification method reference:

Modifiers and types Methods and Instructions
static VerificationAfterDelay after(long millis)Validation is triggered after a given number of milliseconds, allowing testing of asynchronous code.
static VerificationMode atLeast(int minNumberOfInvocations)Allow validation of at least X calls.
static VerificationMode atLeastOnce()Allows validation of at least one invocation.
static VerificationMode atMost(int maxNumberOfInvocations)Allows validation up to X calls.
static VerificationMode atMostOnce()Validation for up to one invocation is allowed.
static VerificationMode calls(int wantedNumberOfInvocations)Allows sequential validation of non-greedy calls.
static Object[] ignoreStubs(Object... mocks)For validation, ignore the stub method of the given mock.
static InOrder inOrder(Object... mocks)createInOrderObject that allows you to mock out in sequence.
static LenientStubber lenient()Loose stub, bypassing “strict stub” validation (see Resources)Strictness.STRICT_STUBS).
static VerificationMode never() times(0)Alias, seetimes(int)
static VerificationMode only()Allows you to check if a given method is called only once.
static <T> void reset(T... mocks)Smart Mockito users rarely use this feature because they know it could be a sign of poor testing.
static VerificationWithTimeout timeout(long millis)Validation is triggered over and over again, up to a given number of milliseconds, allowing testing of asynchronous code.
static VerificationMode times(int wantedNumberOfInvocations)Allows you to verify the exact number of calls.
static void validateMockitoUsage()First, if you have any questions, I encourage you to read the Mockito FAQ:Github.com/mockito/moc…
static <T> T verify(T mock)Validate some behaviorIt happened once.
static <T> T verify(T mock, VerificationMode mode)Verify that some behavior occurred at least once/exactly how many times/never occurred.
static void verifyNoInteractions(Object... mocks)Verify that no interaction occurs on a given simulation.
static void verifyNoMoreInteractions(Object... mocks)Checks for any unvalidated interactions with any given simulation.

Useful operations in Mockito

  • 17. Resetting mock (since 1.8.0)

    • Mockito would forget all interactions and stubs.
  • 18. Use of troubleshooting and validation frameworks (since 1.8.0)

  • 19. Aliases for Behavior-driven Development (since 1.8.0)

  • 20. Serializable mocks (since 1.8.1)

  • 24. Single-line stubs (since 1.9.0)

  • 25. Ignore stub validation (since 1.9.0)

  • 26. MockingDetails (2.2.x improvement)

  • 27. Delegate calls to real objects (since 1.9.5)

  • 28.MockMaker API (as of 1.9.5)

  • 29.BDD style validation (since 1.10.0)

  • Mockito Mockito can be serialized/deserialized across class loaders (since 1.10.0)

  • 34. Enable or disable switcher plug-ins (since Oct 1, 2015)

  • 36.Java 8 Lambda matcher support (since 2.1.0)

  • 41. High-level public API for framework integration (since 2.10.+)

  • 42. New API for integration: Listening for validation start events (since 2.11.+)

  • 43. New API for integration: MockitoSession available for testing frameworks (since 2.15.+)

  • 44. Have been abandoned, org. Mockito. Plugins. InstantiatorProvider because it will leak internal API. It is replaced with org. Mockito. Plugins. InstantiatorProvider2 (Since 2.15.4)

  • 45. New JUnit Jupiter (JUnit5+) extension

  • 46. New mockito.lenient () and mockSettings.lenient () methods (since 2.20.0)

  • 47. New API for clearing mock state in inline mocks (since 2.25.0)

Five: reference

Mockito Javadoc

Modifiers and types Methods and Instructions
static VerificationAfterDelay after(long millis)Validation is triggered after a given number of milliseconds, allowing testing of asynchronous code.
static VerificationMode atLeast(int minNumberOfInvocations)Allow validation of at least X calls.
static VerificationMode atLeastOnce()Allows validation of at least one invocation.
static VerificationMode atMost(int maxNumberOfInvocations)Allows validation up to X calls.
static VerificationMode atMostOnce()Validation for up to one invocation is allowed.
static VerificationMode calls(int wantedNumberOfInvocations)Allows sequential validation of non-greedy calls.
static void clearAllCaches()Clear all mocks, type caching, and detection.
static <T> void clearInvocations(T... mocks)Use this method to clear the call only if the stub is unimportant.
static VerificationMode description(String description)Add a note to print when validation fails.
static Stubber doAnswer(Answer answer)When you want and genericAnswerUsed with the stub void methoddoAnswer().
static Stubber doCallRealMethod()usedoCallRealMethod()Will call (execute) the real method.
static Stubber doNothing()usedoNothing()Setting the void method does nothing.
static Stubber doReturn(Object toBeReturned)In those rare cases, you can’twhen(Object)When usingdoReturn().
static Stubber doReturn(Object toBeReturned, Object... toBeReturnedNext)withdoReturn(Object)Same, but continuous return values can be set.
static Stubber doThrow(Class<? extends Throwable> toBeThrown)Used when you want to stub the void method and throw an exceptiondoThrow().
static Stubber doThrow(Class<? extends Throwable> toBeThrown, Class<? extends Throwable>... toBeThrownNext)withdoThrow(Class)Same, but you can set successive exceptions.
static Stubber doThrow(Throwable... toBeThrown)Used when you want to stub the void method and throw an exceptiondoThrow()Supports continuous exception throwing.
static MockitoFramework framework()For power users or framework integrators.
static Object[] ignoreStubs(Object... mocks)For validation, ignore the stub method of the given mock.
static InOrder inOrder(Object... mocks)createInOrderObject that allows you to mock out in sequence.
static LenientStubber lenient()Loose stub, bypassing “strict stub” validation (see Resources)Strictness.STRICT_STUBS).
static <T> T mock(Class<T> classToMock)Create a mock object for the given class or interface.
static <T> T mock(Class<T> classToMock, Answer defaultAnswer)Create a mock to interact with the specified Answer policy.
static <T> T mock(Class<T> classToMock, MockSettings mockSettings)Create a mock with some non-standard Settings.
static <T> T mock(Class<T> classToMock, String name)Specify the mock name.
static <T> MockedConstruction<T> mockConstruction(Class<T> classToMock)Create thread-local mock controllers for all constructors of a given class.
static <T> MockedConstruction<T> mockConstruction(Class<T> classToMock, java.util.function.Function<MockedConstruction.Context,MockSettings> mockSettingsFactory)Create thread-local mock controllers for all constructors of a given class.
static <T> MockedConstruction<T> mockConstruction(Class<T> classToMock, java.util.function.Function<MockedConstruction.Context,MockSettings> mockSettingsFactory, MockedConstruction.MockInitializer<T> mockInitializer)Create thread-local mock controllers for all constructors of a given class.
static <T> MockedConstruction<T> mockConstruction(Class<T> classToMock, MockedConstruction.MockInitializer<T> mockInitializer)Create thread-local mock controllers for all constructors of a given class.
static <T> MockedConstruction<T> mockConstruction(Class<T> classToMock, MockSettings mockSettings)Create thread-local mock controllers for all constructors of a given class.
static <T> MockedConstruction<T> mockConstruction(Class<T> classToMock, MockSettings mockSettings, MockedConstruction.MockInitializer<T> mockInitializer)Create thread-local mock controllers for all constructors of a given class.
static <T> MockedConstruction<T> mockConstructionWithAnswer(Class<T> classToMock, Answer defaultAnswer, Answer... additionalAnswers)Create thread-local mock controllers for all constructors of a given class.
static MockingDetails mockingDetails(Object toInspect)Returns a MockingDetails instance that allows you to examine a specific object for information about Mockito.
static MockitoSessionBuilder mockitoSession() MockitoSessionIs an optional, highly recommended feature that helps drive clearer testing by eliminating boilerplate code and adding additional validation.
static <T> MockedStatic<T> mockStatic(Class<T> classToMock)Create thread-local mock controllers for all static methods of a given class or interface.
static <T> MockedStatic<T> mockStatic(Class<T> classToMock, Answer defaultAnswer)Create thread-local mock controllers for all static methods of a given class or interface.
static <T> MockedStatic<T> mockStatic(Class<T> classToMock, MockSettings mockSettings)Create thread-local mock controllers for all static methods of a given class or interface.
static <T> MockedStatic<T> mockStatic(Class<T> classToMock, String name)Create thread-local mock controllers for all static methods of a given class or interface.
static VerificationMode never() times(0)Alias, seetimes(int)
static VerificationMode only()Allows you to check if a given method is called only once.
static <T> void reset(T... mocks)Smart Mockito users rarely use this feature because they know it could be a sign of poor testing.
static <T> T spy(Class<T> classToSpy)Please refer to the documentationspy(Object).
static <T> T spy(T object)Create monitoring of real objects.
static VerificationWithTimeout timeout(long millis)Validation is triggered over and over again, up to a given number of milliseconds, allowing testing of asynchronous code.
static VerificationMode times(int wantedNumberOfInvocations)Allows you to verify the exact number of calls.
static void validateMockitoUsage()First, if you have any questions, I encourage you to read the Mockito FAQ:https : //github.com/mockito/mockito/wiki/FAQ
static <T> T verify(T mock)Validate some behaviorIt happened once.
static <T> T verify(T mock, VerificationMode mode)Verify that some behavior occurred at least once/exactly how many times/never occurred.
static void verifyNoInteractions(Object... mocks)Verify that no interaction occurs on a given simulation.
static void verifyNoMoreInteractions(Object... mocks)Checks for any unvalidated interactions with any given simulation.
static void verifyZeroInteractions(Object... mocks)Have been abandoned. Start with 3.0.1. Please migrate your code toverifyNoInteractions(Object...)
static <T> OngoingStubbing<T> when(T methodCall)Create a stub for the method.
static MockSettings withSettings()Allow mock creation using other mock Settings.
    Mockito.after(100);
    Mockito.atLeast();
    Mockito.atLeastOnce();
    Mockito.atMost();
    Mockito.atMostOnce();
    Mockito.calls();
    Mockito.clearAllCaches();
    Mockito.clearInvocations();
    Mockito.description();
    Mockito.doAnswer();
    Mockito.doCallRealMethod();
    Mockito.doNothing();
    Mockito.doReturn();
    Mockito.doReturn(null,null);
    Mockito.doThrow(Object.class);
    Mockito.doThrow(null,null);
    Mockito.doThrow(new Exception())
    Mockito.framework()
    Mockito.ignoreStubs()
    Mockito.inOrder()
    Mockito.lenient()
    Mockito.mock(null)
    Mockito.mock(null,null)
    Mockito.mock(null, new MockSettings())
    Mockito.mock(Object.class,"xx")
    Mockito.mockConstruction(6)
    Mockito.mockConstructionWithAnswer()
    Mockito.mockingDetails()
    Mockito.mockitoSession()
    Mockito.mockStatic(4)
    Mockito.never()
    Mockito.only()
    Mockito.reset();
    Mockito.spy(2)
    Mockito.timeout()
    Mockito.times()
    Mockito.validateMockitoUsage();
    Mockito.verify(2)
    Mockito.verifyNoInteractions();
    Mockito.verifyNoMoreInteractions();
    Mockito.verifyZeroInteractions();
    Mockito.when()
    Mockito.withSettings()
Copy the code