Package org.mockito

Interface MockitoSession


@NotExtensible public interface MockitoSession
MockitoSession is an optional, highly recommended feature that drives writing cleaner tests by eliminating boilerplate code and adding extra validation. If you already use MockitoJUnitRunner or MockitoRule *you don't need* MockitoSession because it is used by the runner/rule.

MockitoSession is a session of mocking, during which the user creates and uses Mockito mocks. Typically, the session is an execution of a single test method. MockitoSession initializes mocks, validates usage and detects incorrect stubbing. When the session is started it must be concluded with finishMocking() otherwise UnfinishedMockingSessionException is triggered when the next session is created.

MockitoSession is useful when you cannot use MockitoJUnitRunner or MockitoRule. Another example is when different JUnit runner is in use (Jukito, Springockito) and it cannot be combined with Mockito's own runner.

Framework integrators are welcome to use MockitoSession and give us feedback by commenting on issue 857.

Example:


 public class ExampleTest {
     @Mock Foo foo;

     //Keeping session object in a field so that we can complete session in 'tear down' method.
     //It is recommended to hide the session object, along with 'setup' and 'tear down' methods in a base class / runner.
     //Keep in mind that you can use Mockito's JUnit runner or rule instead of MockitoSession and get the same behavior.
     MockitoSession mockito;

     @Before public void setup() {
         //initialize session to start mocking
         mockito = Mockito.mockitoSession()
            .initMocks(this)
            .strictness(Strictness.STRICT_STUBS)
            .startMocking();
     }

     @After public void tearDown() {
         //It is necessary to finish the session so that Mockito
         // can detect incorrect stubbing and validate Mockito usage
         //'finishMocking()' is intended to be used in your test framework's 'tear down' method.
         mockito.finishMocking();
     }

     // test methods ...
 }
 

Why to use MockitoSession? What's the difference between MockitoSession, MockitoJUnitRunner, MockitoRule and traditional MockitoAnnotations.openMocks(Object)?

Great questions! There is no need to use MockitoSession if you already use MockitoJUnitRunner or MockitoRule. If you are JUnit user who does not leverage Mockito rule or runner we strongly recommend to do so. Both the runner and the rule support strict stubbing which can really help driving cleaner tests. See MockitoJUnitRunner.StrictStubs and MockitoRule.strictness(Strictness). If you cannot use Mockito's JUnit support MockitoSession exactly is for you! You can automatically take advantage of strict stubbing (Strictness), automatic initialization of annotated mocks (MockitoAnnotations), and extra validation (Mockito.validateMockitoUsage()). If you use Mockito annotations with MockitoAnnotations.openMocks(Object) but not Mockito runner/rule please try out Mockito's JUnit support (runner or rule) or start using MockitoSession. You'll get cleaner tests and better productivity.

Mockito team would really appreciate feedback about MockitoSession API. Help us out by commenting at issue 857.

Since:
2.7.0
  • Method Summary

    Modifier and Type
    Method
    Description
    void
    Must be invoked when the user is done with mocking for given session (test method).
    void
    Must be invoked when the user is done with mocking for given session (test method).
    void
    Changes the strictness of this MockitoSession.
  • Method Details

    • setStrictness

      void setStrictness(Strictness strictness)
      Changes the strictness of this MockitoSession. The new strictness will be applied to operations on mocks and checks performed by finishMocking(). This method is used behind the hood by MockitoRule.strictness(Strictness) method. In most healthy tests, this method is not needed. We keep it for edge cases and when you really need to change strictness in given test method. For use cases see Javadoc for PotentialStubbingProblem class.
      Parameters:
      strictness - new strictness for this session.
      Since:
      2.15.0
    • finishMocking

      void finishMocking()
      Must be invoked when the user is done with mocking for given session (test method). It detects unused stubbings and may throw UnnecessaryStubbingException or emit warnings (MockitoHint) depending on the Strictness level. The method also detects incorrect Mockito usage via Mockito.validateMockitoUsage().

      In order to implement Strictness Mockito session keeps track of mocking using MockitoListener. This method cleans up the listeners and ensures there is no leftover state after the session finishes. It is necessary to invoke this method to conclude mocking session. For more information about session lifecycle see MockitoSessionBuilder.startMocking().

      This method is intended to be used in your test framework's 'tear down' method. In the case of JUnit it is the "@After" method.

      For example, see javadoc for MockitoSession.

      Since:
      2.7.0
      See Also:
    • finishMocking

      void finishMocking(Throwable failure)
      Must be invoked when the user is done with mocking for given session (test method). When a failure is specified, certain checks are disabled to avoid confusion that may arise because there are multiple competing failures. Other than that, this method behaves exactly like finishMocking().

      This method is intended to be used by framework integrations. When using MockitoSession directly, most users should rather use finishMocking(). MockitoRule uses this method behind the hood.

      Parameters:
      failure - the exception that caused the test to fail; passing null is permitted
      Since:
      2.15.0
      See Also: