Class MockitoTestNGListener

  • All Implemented Interfaces:
    org.testng.IInvokedMethodListener, org.testng.ITestNGListener

    public class MockitoTestNGListener
    extends java.lang.Object
    implements org.testng.IInvokedMethodListener

    Mockito TestNG Listener, this listener initializes mocks and handles strict stubbing, it is similar to JUnit MockitoJUnitRunner, MockitoRule, MockitoExtension and adds the following behavior to your test:

    • Before any test method or a configuration method @BeforeMethod MockitoSession is started by:
      
               Mockito.mockitoSession()
                .initMocks(testInstance)
                .strictness(Strictness.STRICT_STUBS)
                .startMocking()
               
      See javadoc MockitoSession
    • After each test method MockitoSession.finishMocking() is called.

    Example usage:

    
     @Listeners(MockitoTestNGListener.class)
     public class ExampleTest {
    
         @Mock
         private List list;
    
         @Test
         public void shouldDoSomething() {
             list.add(100);
         }
     }
     

    By default MockitoSession is started with Strictness.STRICT_STUBS. You can change this behavior by adding MockitoSettings to your test class.

    
     @Listeners(MockitoTestNGListener.class)
     @MockitoSettings(strictness = Strictness.WARN)
     public class ExampleTest {
      ...
     }
     

    MockitoTestNGListener not working with parallel tests, more information https://github.com/mockito/mockito-testng/issues/20

    • Method Summary

      All Methods Instance Methods Concrete Methods 
      Modifier and Type Method Description
      void afterInvocation​(org.testng.IInvokedMethod method, org.testng.ITestResult testResult)  
      void beforeInvocation​(org.testng.IInvokedMethod method, org.testng.ITestResult testResult)  
      protected boolean hasMockitoTestNGListener​(org.testng.ITestResult testResult)  
      • Methods inherited from class java.lang.Object

        clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait
      • Methods inherited from interface org.testng.IInvokedMethodListener

        afterInvocation, beforeInvocation
    • Constructor Detail

      • MockitoTestNGListener

        public MockitoTestNGListener()
    • Method Detail

      • beforeInvocation

        public void beforeInvocation​(org.testng.IInvokedMethod method,
                                     org.testng.ITestResult testResult)
        Specified by:
        beforeInvocation in interface org.testng.IInvokedMethodListener
      • afterInvocation

        public void afterInvocation​(org.testng.IInvokedMethod method,
                                    org.testng.ITestResult testResult)
        Specified by:
        afterInvocation in interface org.testng.IInvokedMethodListener
      • hasMockitoTestNGListener

        protected boolean hasMockitoTestNGListener​(org.testng.ITestResult testResult)