Best Mockito code snippet using org.mockito.Mockito.framework
Source:AuditEventTest.java  
1package io.coodoo.framework.audit.entity;2import java.time.LocalDateTime;3import java.util.ArrayList;4import java.util.Arrays;5import java.util.List;6import javax.persistence.EntityManager;7import javax.persistence.NamedQueries;8import javax.persistence.NamedQuery;9import javax.persistence.Query;10public class AuditEventTest {11    /**12     * Tests that query 'AuditEvent.getAllEvents' has not changed since this test had been created. If this test fails, you should consider re-generating ALL13     * methods created from that query as they may be out-dated.14     *15     */16    @SuppressWarnings({"unchecked", "rawtypes", "null"})17    @org.junit.Test18    public void testGetAllEventsQueryUnchanged() {19        List annotations = new ArrayList();20        NamedQuery namedQueryAnnotation = io.coodoo.framework.audit.entity.AuditEvent.class.getAnnotation(NamedQuery.class);21        if (namedQueryAnnotation == null) {22            NamedQueries namedQueriesAnnotation = io.coodoo.framework.audit.entity.AuditEvent.class.getAnnotation(NamedQueries.class);23            if (namedQueriesAnnotation != null) {24                annotations.addAll(Arrays.asList(namedQueriesAnnotation.value()));25            }26        } else {27            annotations.add(namedQueryAnnotation);28        }29        NamedQuery queryUnderTest = null;30        for (Object obj : annotations) {31            NamedQuery query = (NamedQuery) obj;32            if (query.name().equals("AuditEvent.getAllEvents")) {33                queryUnderTest = query;34                break;35            }36        }37        if (queryUnderTest == null) {38            org.junit.Assert.fail("Query AuditEvent.getAllEvents does not exist anymore.");39        }40        String queryText = queryUnderTest.query();41        // Minor changes with whitespace are ignored42        queryText = queryText.trim().replace('\t', ' ').replace('\n', ' ').replace('\r', ' ');43        while (queryText.contains("  ")) {44            queryText = queryText.replace("  ", " ");45        }46        org.junit.Assert.assertEquals(47                        "There's a change in the query string. Generated methods may not fit to the query anymore. Change from 'SELECT av FROM AuditEvent av WHERE av.entity = :entity ORDER BY av.createdAt DESC' to '"48                                        + queryText + "'",49                        "SELECT av FROM AuditEvent av WHERE av.entity = :entity ORDER BY av.createdAt DESC", queryText);50    }51    /**52     * Tests that call and query are consistent for query 'AuditEvent.getAllEvents'.53     *54     */55    @org.junit.Test56    public void testGetAllEvents() {57        Query query = org.mockito.Mockito.mock(Query.class);58        EntityManager entityManager = org.mockito.Mockito.mock(EntityManager.class);59        org.mockito.BDDMockito.given(entityManager.createNamedQuery("AuditEvent.getAllEvents")).willReturn(query);60        String entity = "0";61        org.mockito.BDDMockito.given(query.setParameter("entity", entity)).willReturn(query);62        // Call63        io.coodoo.framework.audit.entity.AuditEvent.getAllEvents(entityManager, entity);64        // Verification65        org.mockito.BDDMockito.verify(entityManager, org.mockito.Mockito.times(1)).createNamedQuery("AuditEvent.getAllEvents");66        org.mockito.BDDMockito.verify(query, org.mockito.Mockito.times(1)).setParameter("entity", entity);67        org.mockito.BDDMockito.verify(query, org.mockito.Mockito.times(1)).getResultList();68    }69    /**70     * Tests that all classes and members/fields used in query 'AuditEvent.getAllEvents' still exist.71     *72     */73    @org.junit.Test74    public void testGetAllEventsVerifyFields() {75        String[][] classesFieldsAndTypes = new String[3][4];76        classesFieldsAndTypes[0][0] = "av";77        classesFieldsAndTypes[0][1] = "io.coodoo.framework.audit.entity.AuditEvent";78        classesFieldsAndTypes[1][0] = "av.createdAt";79        classesFieldsAndTypes[1][1] = "io.coodoo.framework.audit.entity.AuditEvent";80        classesFieldsAndTypes[1][2] = "createdAt";81        classesFieldsAndTypes[1][3] = "java.time.LocalDateTime";82        classesFieldsAndTypes[2][0] = "av.entity";83        classesFieldsAndTypes[2][1] = "io.coodoo.framework.audit.entity.AuditEvent";84        classesFieldsAndTypes[2][2] = "entity";85        classesFieldsAndTypes[2][3] = "java.lang.String";86        for (String[] testcase : classesFieldsAndTypes) {87            String fieldPath = testcase[0];88            String className = testcase[1];89            String fieldName = testcase[2];90            String fieldType = testcase[3];91            try {92                Class<?> clazz = Class.forName(className);93                if (fieldName != null) {94                    boolean fieldFound = false;95                    do {96                        for (java.lang.reflect.Field field : clazz.getDeclaredFields()) {97                            if (field.getName().equals(fieldName)) {98                                if (fieldType != null && !field.getType().getName().equals(fieldType)) {99                                    org.junit.Assert.fail("Error checking path " + fieldPath + " in query AuditEvent.getAllEvents: The field " + clazz.getName()100                                                    + "." + field + " does not have the type " + fieldType + " (anymore)");101                                }102                                fieldFound = true;103                                break;104                            }105                        }106                        clazz = clazz.getSuperclass();107                    } while (!fieldFound && clazz != null);108                    if (!fieldFound) {109                        org.junit.Assert.fail("Error checking path " + fieldPath + " in query AuditEvent.getAllEvents: The field " + className + "." + fieldName110                                        + " does not exist (anymore)");111                    }112                }113            } catch (ClassNotFoundException e) {114                org.junit.Assert.fail(115                                "Error checking path " + fieldPath + " in query AuditEvent.getAllEvents: The class " + className + " does not exist (anymore)");116            }117        }118    }119    /**120     * Tests that query 'AuditEvent.getAllEventsForId' has not changed since this test had been created. If this test fails, you should consider re-generating121     * ALL methods created from that query as they may be out-dated.122     *123     */124    @SuppressWarnings({"unchecked", "rawtypes", "null"})125    @org.junit.Test126    public void testGetAllEventsForIdQueryUnchanged() {127        List annotations = new ArrayList();128        NamedQuery namedQueryAnnotation = io.coodoo.framework.audit.entity.AuditEvent.class.getAnnotation(NamedQuery.class);129        if (namedQueryAnnotation == null) {130            NamedQueries namedQueriesAnnotation = io.coodoo.framework.audit.entity.AuditEvent.class.getAnnotation(NamedQueries.class);131            if (namedQueriesAnnotation != null) {132                annotations.addAll(Arrays.asList(namedQueriesAnnotation.value()));133            }134        } else {135            annotations.add(namedQueryAnnotation);136        }137        NamedQuery queryUnderTest = null;138        for (Object obj : annotations) {139            NamedQuery query = (NamedQuery) obj;140            if (query.name().equals("AuditEvent.getAllEventsForId")) {141                queryUnderTest = query;142                break;143            }144        }145        if (queryUnderTest == null) {146            org.junit.Assert.fail("Query AuditEvent.getAllEventsForId does not exist anymore.");147        }148        String queryText = queryUnderTest.query();149        // Minor changes with whitespace are ignored150        queryText = queryText.trim().replace('\t', ' ').replace('\n', ' ').replace('\r', ' ');151        while (queryText.contains("  ")) {152            queryText = queryText.replace("  ", " ");153        }154        org.junit.Assert.assertEquals(155                        "There's a change in the query string. Generated methods may not fit to the query anymore. Change from 'SELECT av FROM AuditEvent av WHERE av.entity = :entity AND av.entityId = :entityId ORDER BY av.createdAt DESC' to '"156                                        + queryText + "'",157                        "SELECT av FROM AuditEvent av WHERE av.entity = :entity AND av.entityId = :entityId ORDER BY av.createdAt DESC", queryText);158    }159    /**160     * Tests that call and query are consistent for query 'AuditEvent.getAllEventsForId'.161     *162     */163    @org.junit.Test164    public void testGetAllEventsForId() {165        Query query = org.mockito.Mockito.mock(Query.class);166        EntityManager entityManager = org.mockito.Mockito.mock(EntityManager.class);167        org.mockito.BDDMockito.given(entityManager.createNamedQuery("AuditEvent.getAllEventsForId")).willReturn(query);168        String entity = "0";169        org.mockito.BDDMockito.given(query.setParameter("entity", entity)).willReturn(query);170        Long entityId = java.lang.Long.valueOf(1);171        org.mockito.BDDMockito.given(query.setParameter("entityId", entityId)).willReturn(query);172        // Call173        io.coodoo.framework.audit.entity.AuditEvent.getAllEventsForId(entityManager, entity, entityId);174        // Verification175        org.mockito.BDDMockito.verify(entityManager, org.mockito.Mockito.times(1)).createNamedQuery("AuditEvent.getAllEventsForId");176        org.mockito.BDDMockito.verify(query, org.mockito.Mockito.times(1)).setParameter("entity", entity);177        org.mockito.BDDMockito.verify(query, org.mockito.Mockito.times(1)).setParameter("entityId", entityId);178        org.mockito.BDDMockito.verify(query, org.mockito.Mockito.times(1)).getResultList();179    }180    /**181     * Tests that all classes and members/fields used in query 'AuditEvent.getAllEventsForId' still exist.182     *183     */184    @org.junit.Test185    public void testGetAllEventsForIdVerifyFields() {186        String[][] classesFieldsAndTypes = new String[4][4];187        classesFieldsAndTypes[0][0] = "av";188        classesFieldsAndTypes[0][1] = "io.coodoo.framework.audit.entity.AuditEvent";189        classesFieldsAndTypes[1][0] = "av.createdAt";190        classesFieldsAndTypes[1][1] = "io.coodoo.framework.audit.entity.AuditEvent";191        classesFieldsAndTypes[1][2] = "createdAt";192        classesFieldsAndTypes[1][3] = "java.time.LocalDateTime";193        classesFieldsAndTypes[2][0] = "av.entity";194        classesFieldsAndTypes[2][1] = "io.coodoo.framework.audit.entity.AuditEvent";195        classesFieldsAndTypes[2][2] = "entity";196        classesFieldsAndTypes[2][3] = "java.lang.String";197        classesFieldsAndTypes[3][0] = "av.entityId";198        classesFieldsAndTypes[3][1] = "io.coodoo.framework.audit.entity.AuditEvent";199        classesFieldsAndTypes[3][2] = "entityId";200        classesFieldsAndTypes[3][3] = "java.lang.Long";201        for (String[] testcase : classesFieldsAndTypes) {202            String fieldPath = testcase[0];203            String className = testcase[1];204            String fieldName = testcase[2];205            String fieldType = testcase[3];206            try {207                Class<?> clazz = Class.forName(className);208                if (fieldName != null) {209                    boolean fieldFound = false;210                    do {211                        for (java.lang.reflect.Field field : clazz.getDeclaredFields()) {212                            if (field.getName().equals(fieldName)) {213                                if (fieldType != null && !field.getType().getName().equals(fieldType)) {214                                    org.junit.Assert.fail("Error checking path " + fieldPath + " in query AuditEvent.getAllEventsForId: The field "215                                                    + clazz.getName() + "." + field + " does not have the type " + fieldType + " (anymore)");216                                }217                                fieldFound = true;218                                break;219                            }220                        }221                        clazz = clazz.getSuperclass();222                    } while (!fieldFound && clazz != null);223                    if (!fieldFound) {224                        org.junit.Assert.fail("Error checking path " + fieldPath + " in query AuditEvent.getAllEventsForId: The field " + className + "."225                                        + fieldName + " does not exist (anymore)");226                    }227                }228            } catch (ClassNotFoundException e) {229                org.junit.Assert.fail("Error checking path " + fieldPath + " in query AuditEvent.getAllEventsForId: The class " + className230                                + " does not exist (anymore)");231            }232        }233    }234    /**235     * Tests that query 'AuditEvent.getLatestEvent' has not changed since this test had been created. If this test fails, you should consider re-generating ALL236     * methods created from that query as they may be out-dated.237     *238     */239    @SuppressWarnings({"unchecked", "rawtypes", "null"})240    @org.junit.Test241    public void testGetLatestEventQueryUnchanged() {242        List annotations = new ArrayList();243        NamedQuery namedQueryAnnotation = io.coodoo.framework.audit.entity.AuditEvent.class.getAnnotation(NamedQuery.class);244        if (namedQueryAnnotation == null) {245            NamedQueries namedQueriesAnnotation = io.coodoo.framework.audit.entity.AuditEvent.class.getAnnotation(NamedQueries.class);246            if (namedQueriesAnnotation != null) {247                annotations.addAll(Arrays.asList(namedQueriesAnnotation.value()));248            }249        } else {250            annotations.add(namedQueryAnnotation);251        }252        NamedQuery queryUnderTest = null;253        for (Object obj : annotations) {254            NamedQuery query = (NamedQuery) obj;255            if (query.name().equals("AuditEvent.getLatestEvent")) {256                queryUnderTest = query;257                break;258            }259        }260        if (queryUnderTest == null) {261            org.junit.Assert.fail("Query AuditEvent.getLatestEvent does not exist anymore.");262        }263        String queryText = queryUnderTest.query();264        // Minor changes with whitespace are ignored265        queryText = queryText.trim().replace('\t', ' ').replace('\n', ' ').replace('\r', ' ');266        while (queryText.contains("  ")) {267            queryText = queryText.replace("  ", " ");268        }269        org.junit.Assert.assertEquals(270                        "There's a change in the query string. Generated methods may not fit to the query anymore. Change from 'SELECT av FROM AuditEvent av WHERE av.entity = :entity AND av.entityId = :entityId AND av.createdAt >= :fromDate ORDER BY av.createdAt DESC' to '"271                                        + queryText + "'",272                        "SELECT av FROM AuditEvent av WHERE av.entity = :entity AND av.entityId = :entityId AND av.createdAt >= :fromDate ORDER BY av.createdAt DESC",273                        queryText);274    }275    /**276     * Tests that call and query are consistent for query 'AuditEvent.getLatestEvent' - no result.277     *278     */279    @org.junit.Test280    public void testGetLatestEventEmptyResult() {281        Query query = org.mockito.Mockito.mock(Query.class);282        EntityManager entityManager = org.mockito.Mockito.mock(EntityManager.class);283        org.mockito.BDDMockito.given(entityManager.createNamedQuery("AuditEvent.getLatestEvent")).willReturn(query);284        @SuppressWarnings("rawtypes")285        List results = new ArrayList();286        org.mockito.BDDMockito.given(query.getResultList()).willReturn(results);287        String entity = "0";288        org.mockito.BDDMockito.given(query.setParameter("entity", entity)).willReturn(query);289        Long entityId = java.lang.Long.valueOf(1);290        org.mockito.BDDMockito.given(query.setParameter("entityId", entityId)).willReturn(query);291        LocalDateTime fromDate = null;292        org.mockito.BDDMockito.given(query.setParameter("fromDate", fromDate)).willReturn(query);293        org.mockito.BDDMockito.given(query.setMaxResults(1)).willReturn(query);294        // Call295        AuditEvent result = io.coodoo.framework.audit.entity.AuditEvent.getLatestEvent(entityManager, entity, entityId, fromDate);296        // Verification297        org.mockito.BDDMockito.verify(entityManager, org.mockito.Mockito.times(1)).createNamedQuery("AuditEvent.getLatestEvent");298        org.mockito.BDDMockito.verify(query, org.mockito.Mockito.times(1)).setParameter("entity", entity);299        org.mockito.BDDMockito.verify(query, org.mockito.Mockito.times(1)).setParameter("entityId", entityId);300        org.mockito.BDDMockito.verify(query, org.mockito.Mockito.times(1)).setParameter("fromDate", fromDate);301        org.mockito.BDDMockito.verify(query, org.mockito.Mockito.times(1)).getResultList();302        org.junit.Assert.assertNull("Result should be null if list is empty", result);303    }304    /**305     * Tests that call and query are consistent for query 'AuditEvent.getLatestEvent' - one result.306     *307     */308    @SuppressWarnings({"unchecked", "rawtypes"})309    @org.junit.Test310    public void testGetLatestEventOneResult() {311        Query query = org.mockito.Mockito.mock(Query.class);312        EntityManager entityManager = org.mockito.Mockito.mock(EntityManager.class);313        org.mockito.BDDMockito.given(entityManager.createNamedQuery("AuditEvent.getLatestEvent")).willReturn(query);314        List results = new java.util.ArrayList();315        AuditEvent first = org.mockito.Mockito.mock(AuditEvent.class);316        AuditEvent second = org.mockito.Mockito.mock(AuditEvent.class);317        results.add(first);318        results.add(second);319        org.mockito.BDDMockito.given(query.getResultList()).willReturn(results);320        String entity = "0";321        org.mockito.BDDMockito.given(query.setParameter("entity", entity)).willReturn(query);322        Long entityId = java.lang.Long.valueOf(1);323        org.mockito.BDDMockito.given(query.setParameter("entityId", entityId)).willReturn(query);324        LocalDateTime fromDate = null;325        org.mockito.BDDMockito.given(query.setParameter("fromDate", fromDate)).willReturn(query);326        org.mockito.BDDMockito.given(query.setMaxResults(1)).willReturn(query);327        // Call328        AuditEvent result = io.coodoo.framework.audit.entity.AuditEvent.getLatestEvent(entityManager, entity, entityId, fromDate);329        // Verification330        org.mockito.BDDMockito.verify(entityManager, org.mockito.Mockito.times(1)).createNamedQuery("AuditEvent.getLatestEvent");331        org.mockito.BDDMockito.verify(query, org.mockito.Mockito.times(1)).setParameter("entity", entity);332        org.mockito.BDDMockito.verify(query, org.mockito.Mockito.times(1)).setParameter("entityId", entityId);333        org.mockito.BDDMockito.verify(query, org.mockito.Mockito.times(1)).setParameter("fromDate", fromDate);334        org.mockito.BDDMockito.verify(query, org.mockito.Mockito.times(1)).getResultList();335        org.junit.Assert.assertEquals("Result not the first of list.", first, result);336    }337    /**338     * Tests that all classes and members/fields used in query 'AuditEvent.getLatestEvent' still exist.339     *340     */341    @org.junit.Test342    public void testGetLatestEventVerifyFields() {343        String[][] classesFieldsAndTypes = new String[4][4];344        classesFieldsAndTypes[0][0] = "av";345        classesFieldsAndTypes[0][1] = "io.coodoo.framework.audit.entity.AuditEvent";346        classesFieldsAndTypes[1][0] = "av.createdAt";347        classesFieldsAndTypes[1][1] = "io.coodoo.framework.audit.entity.AuditEvent";348        classesFieldsAndTypes[1][2] = "createdAt";349        classesFieldsAndTypes[1][3] = "java.time.LocalDateTime";350        classesFieldsAndTypes[2][0] = "av.entity";351        classesFieldsAndTypes[2][1] = "io.coodoo.framework.audit.entity.AuditEvent";352        classesFieldsAndTypes[2][2] = "entity";353        classesFieldsAndTypes[2][3] = "java.lang.String";354        classesFieldsAndTypes[3][0] = "av.entityId";355        classesFieldsAndTypes[3][1] = "io.coodoo.framework.audit.entity.AuditEvent";356        classesFieldsAndTypes[3][2] = "entityId";357        classesFieldsAndTypes[3][3] = "java.lang.Long";358        for (String[] testcase : classesFieldsAndTypes) {359            String fieldPath = testcase[0];360            String className = testcase[1];361            String fieldName = testcase[2];362            String fieldType = testcase[3];363            try {364                Class<?> clazz = Class.forName(className);365                if (fieldName != null) {366                    boolean fieldFound = false;367                    do {368                        for (java.lang.reflect.Field field : clazz.getDeclaredFields()) {369                            if (field.getName().equals(fieldName)) {...Source:StaticMockingExperimentTest.java  
...24import org.mockito.invocation.MockHandler;25import org.mockitoutil.TestBase;26/**27 * This test is an experimental use of Mockito API to simulate static mocking.28 * Other frameworks can use it to build good support for static mocking.29 * Keep in mind that clean code never needs to mock static methods.30 * This test is a documentation how it can be done using current public API of Mockito.31 * This test is not only an experiment it also provides coverage for32 * some of the advanced public API exposed for framework integrators.33 * <p>34 * For more rationale behind this experimental test35 * <a href="https://www.linkedin.com/pulse/mockito-vs-powermock-opinionated-dogmatic-static-mocking-faber">see the article</a>.36 */37public class StaticMockingExperimentTest extends TestBase {38    Foo mock = Mockito.mock(Foo.class);39    MockHandler handler = Mockito.mockingDetails(mock).getMockHandler();40    Method staticMethod;41    InvocationFactory.RealMethodBehavior realMethod =42            new InvocationFactory.RealMethodBehavior() {43                @Override44                public Object call() throws Throwable {45                    return null;46                }47            };48    @Before49    public void before() throws Throwable {50        staticMethod = Foo.class.getDeclaredMethod("staticMethod", String.class);51    }52    @SuppressWarnings({"CheckReturnValue", "MockitoUsage"})53    @Test54    public void verify_static_method() throws Throwable {55        // register staticMethod call on mock56        Invocation invocation =57                Mockito.framework()58                        .getInvocationFactory()59                        .createInvocation(60                                mock,61                                withSettings().build(Foo.class),62                                staticMethod,63                                realMethod,64                                "some arg");65        handler.handle(invocation);66        // verify staticMethod on mock67        // Mockito cannot capture static methods so we will simulate this scenario in 3 steps:68        // 1. Call standard 'verify' method. Internally, it will add verificationMode to the thread69        // local state.70        //  Effectively, we indicate to Mockito that right now we are about to verify a method call71        // on this mock.72        verify(mock);73        // 2. Create the invocation instance using the new public API74        //  Mockito cannot capture static methods but we can create an invocation instance of that75        // static invocation76        Invocation verification =77                Mockito.framework()78                        .getInvocationFactory()79                        .createInvocation(80                                mock,81                                withSettings().build(Foo.class),82                                staticMethod,83                                realMethod,84                                "some arg");85        // 3. Make Mockito handle the static method invocation86        //  Mockito will find verification mode in thread local state and will try verify the87        // invocation88        handler.handle(verification);89        // verify zero times, method with different argument90        verify(mock, times(0));91        Invocation differentArg =92                Mockito.framework()93                        .getInvocationFactory()94                        .createInvocation(95                                mock,96                                withSettings().build(Foo.class),97                                staticMethod,98                                realMethod,99                                "different arg");100        handler.handle(differentArg);101    }102    @SuppressWarnings({"CheckReturnValue", "MockitoUsage"})103    @Test104    public void verification_failure_static_method() throws Throwable {105        // register staticMethod call on mock106        Invocation invocation =107                Mockito.framework()108                        .getInvocationFactory()109                        .createInvocation(110                                mock,111                                withSettings().build(Foo.class),112                                staticMethod,113                                realMethod,114                                "foo");115        handler.handle(invocation);116        // verify staticMethod on mock117        verify(mock);118        Invocation differentArg =119                Mockito.framework()120                        .getInvocationFactory()121                        .createInvocation(122                                mock,123                                withSettings().build(Foo.class),124                                staticMethod,125                                realMethod,126                                "different arg");127        try {128            handler.handle(differentArg);129            fail();130        } catch (ArgumentsAreDifferent e) {131        }132    }133    @Test134    public void stubbing_static_method() throws Throwable {135        // register staticMethod call on mock136        Invocation invocation =137                Mockito.framework()138                        .getInvocationFactory()139                        .createInvocation(140                                mock,141                                withSettings().build(Foo.class),142                                staticMethod,143                                realMethod,144                                "foo");145        handler.handle(invocation);146        // register stubbing147        when(null).thenReturn("hey");148        // validate stubbed return value149        assertEquals("hey", handler.handle(invocation));150        assertEquals("hey", handler.handle(invocation));151        // default null value is returned if invoked with different argument152        Invocation differentArg =153                Mockito.framework()154                        .getInvocationFactory()155                        .createInvocation(156                                mock,157                                withSettings().build(Foo.class),158                                staticMethod,159                                realMethod,160                                "different arg");161        assertEquals(null, handler.handle(differentArg));162    }163    @Test164    public void do_answer_stubbing_static_method() throws Throwable {165        // register stubbed return value166        Object ignored = doReturn("hey").when(mock);167        // complete stubbing by triggering an invocation that needs to be stubbed168        Invocation invocation =169                Mockito.framework()170                        .getInvocationFactory()171                        .createInvocation(172                                mock,173                                withSettings().build(Foo.class),174                                staticMethod,175                                realMethod,176                                "foo");177        handler.handle(invocation);178        // validate stubbed return value179        assertEquals("hey", handler.handle(invocation));180        assertEquals("hey", handler.handle(invocation));181        // default null value is returned if invoked with different argument182        Invocation differentArg =183                Mockito.framework()184                        .getInvocationFactory()185                        .createInvocation(186                                mock,187                                withSettings().build(Foo.class),188                                staticMethod,189                                realMethod,190                                "different arg");191        assertEquals(null, handler.handle(differentArg));192    }193    @Test194    public void verify_no_more_interactions() throws Throwable {195        // works for now because there are not interactions196        verifyNoMoreInteractions(mock);197        // register staticMethod call on mock198        Invocation invocation =199                Mockito.framework()200                        .getInvocationFactory()201                        .createInvocation(202                                mock,203                                withSettings().build(Foo.class),204                                staticMethod,205                                realMethod,206                                "foo");207        handler.handle(invocation);208        // fails now because we have one static invocation recorded209        try {210            verifyNoMoreInteractions(mock);211            fail();212        } catch (NoInteractionsWanted e) {213        }214    }215    @Test216    public void stubbing_new() throws Throwable {217        Constructor<Foo> ctr = Foo.class.getConstructor(String.class);218        Method adapter = ConstructorMethodAdapter.class.getDeclaredMethods()[0];219        // stub constructor220        Object ignored = doReturn(new Foo("hey!")).when(mock);221        Invocation constructor =222                Mockito.framework()223                        .getInvocationFactory()224                        .createInvocation(225                                mock,226                                withSettings().build(Foo.class),227                                adapter,228                                realMethod,229                                ctr,230                                "foo");231        handler.handle(constructor);232        // test stubbing233        Object result = handler.handle(constructor);234        assertEquals("foo:hey!", result.toString());235        // stubbing miss236        Invocation differentArg =237                Mockito.framework()238                        .getInvocationFactory()239                        .createInvocation(240                                mock,241                                withSettings().build(Foo.class),242                                adapter,243                                realMethod,244                                ctr,245                                "different arg");246        Object result2 = handler.handle(differentArg);247        assertEquals(null, result2);248    }249    @SuppressWarnings({"CheckReturnValue", "MockitoUsage"})250    @Test251    public void verifying_new() throws Throwable {252        Constructor<Foo> ctr = Foo.class.getConstructor(String.class);253        Method adapter = ConstructorMethodAdapter.class.getDeclaredMethods()[0];254        // invoke constructor255        Invocation constructor =256                Mockito.framework()257                        .getInvocationFactory()258                        .createInvocation(259                                mock,260                                withSettings().build(Foo.class),261                                adapter,262                                realMethod,263                                ctr,264                                "matching arg");265        handler.handle(constructor);266        // verify successfully267        verify(mock);268        handler.handle(constructor);269        // verification failure270        verify(mock);271        Invocation differentArg =272                Mockito.framework()273                        .getInvocationFactory()274                        .createInvocation(275                                mock,276                                withSettings().build(Foo.class),277                                adapter,278                                realMethod,279                                ctr,280                                "different arg");281        try {282            handler.handle(differentArg);283            fail();284        } catch (WantedButNotInvoked e) {285            assertThat(e.getMessage()).contains("matching arg").contains("different arg");286        }...Source:VerificationListenerCallBackTest.java  
...28    @Test29    public void should_call_single_listener_on_verify() throws NoSuchMethodException {30        // given31        RememberingListener listener = new RememberingListener();32        MockitoFramework mockitoFramework = Mockito.framework();33        mockitoFramework.addListener(listener);34        Method invocationWanted = Foo.class.getDeclaredMethod("doSomething", String.class);35        Foo foo = mock(Foo.class);36        // when37        VerificationMode never = never();38        verify(foo, never).doSomething("");39        // then40        assertThat(listener).is(notifiedFor(foo, never, invocationWanted));41    }42    @Test43    public void should_call_all_listeners_on_verify() throws NoSuchMethodException {44        // given45        RememberingListener listener1 = new RememberingListener();46        RememberingListener2 listener2 = new RememberingListener2();47        Mockito.framework().addListener(listener1).addListener(listener2);48        Method invocationWanted = Foo.class.getDeclaredMethod("doSomething", String.class);49        Foo foo = mock(Foo.class);50        // when51        VerificationMode never = never();52        verify(foo, never).doSomething("");53        // then54        assertThat(listener1).is(notifiedFor(foo, never, invocationWanted));55        assertThat(listener2).is(notifiedFor(foo, never, invocationWanted));56    }57    @Test58    public void should_not_call_listener_when_verify_was_called_incorrectly() {59        // when60        VerificationListener listener = mock(VerificationListener.class);61        framework().addListener(listener);62        Foo foo = null;63        try {64            verify(foo).doSomething("");65            fail("Exception expected.");66        } catch (Exception e) {67            // then68            verify(listener, never()).onVerification(any(VerificationEvent.class));69        }70    }71    @Test72    public void should_notify_when_verification_throws_type_error() {73        // given74        RememberingListener listener = new RememberingListener();75        MockitoFramework mockitoFramework = Mockito.framework();76        mockitoFramework.addListener(listener);77        Foo foo = mock(Foo.class);78        // when79        try {80            verify(foo).doSomething("");81            fail("Exception expected.");82        } catch (Throwable e) {83            // then84            assertThat(listener.cause).isInstanceOf(MockitoAssertionError.class);85        }86    }87    @Test88    public void should_notify_when_verification_throws_runtime_exception() {89        // given90        RememberingListener listener = new RememberingListener();91        MockitoFramework mockitoFramework = Mockito.framework();92        mockitoFramework.addListener(listener);93        Foo foo = mock(Foo.class);94        // when95        try {96            verify(foo, new RuntimeExceptionVerificationMode()).doSomething("");97            fail("Exception expected.");98        } catch (Throwable e) {99            // then100            assertThat(listener.cause).isInstanceOf(RuntimeException.class);101        }102    }103    @Test104    public void should_call_verification_listeners() {105        // given106        RememberingListener listener = new RememberingListener();107        MockitoFramework mockitoFramework = Mockito.framework();108        mockitoFramework.addListener(listener);109        JUnitCore runner = new JUnitCore();110        // when111        runner.run(VerificationListenerSample.class);112        // then113        assertThat(listener.mock).isNotNull();114        assertThat(listener.mode).isEqualToComparingFieldByField(times(1));115    }116    public static class VerificationListenerSample {117        @Test118        public void verificationTest() {119            Foo foo = mock(Foo.class);120            foo.doSomething("");121            verify(foo).doSomething("");...Source:DefaultMockitoFrameworkTest.java  
1/*2 * Copyright (c) 2017 Mockito contributors3 * This program is made available under the terms of the MIT License.4 */5package org.mockito.internal.framework;6import static org.junit.Assert.assertFalse;7import static org.junit.Assert.assertTrue;8import static org.junit.Assume.assumeTrue;9import static org.mockito.Mockito.any;10import static org.mockito.Mockito.eq;11import static org.mockito.Mockito.mock;12import static org.mockito.Mockito.mockingDetails;13import static org.mockito.Mockito.verify;14import static org.mockito.Mockito.verifyNoMoreInteractions;15import static org.mockito.Mockito.withSettings;16import static org.mockitoutil.ThrowableAssert.assertThat;17import java.util.List;18import java.util.Set;19import org.junit.After;20import org.junit.Test;21import org.mockito.ArgumentMatchers;22import org.mockito.MockSettings;23import org.mockito.StateMaster;24import org.mockito.exceptions.misusing.RedundantListenerException;25import org.mockito.internal.configuration.plugins.Plugins;26import org.mockito.listeners.MockCreationListener;27import org.mockito.listeners.MockitoListener;28import org.mockito.mock.MockCreationSettings;29import org.mockito.plugins.InlineMockMaker;30import org.mockitoutil.TestBase;31public class DefaultMockitoFrameworkTest extends TestBase {32    private DefaultMockitoFramework framework = new DefaultMockitoFramework();33    @After34    public void clearListeners() {35        new StateMaster().clearMockitoListeners();36    }37    @Test(expected = IllegalArgumentException.class)38    public void prevents_adding_null_listener() {39        framework.addListener(null);40    }41    @Test(expected = IllegalArgumentException.class)42    public void prevents_removing_null_listener() {43        framework.removeListener(null);44    }45    @Test46    public void ok_to_remove_unknown_listener() {47        // it is safe to remove listener that was not added before48        framework.removeListener(new MockitoListener() {});49    }50    @Test51    public void ok_to_remove_listener_multiple_times() {52        MockitoListener listener = new MockitoListener() {};53        // when54        framework.addListener(listener);55        // then it is ok to:56        framework.removeListener(listener);57        framework.removeListener(listener);58    }59    @Test60    public void adds_creation_listener() {61        // given creation listener is added62        MockCreationListener listener = mock(MockCreationListener.class);63        framework.addListener(listener);64        // when65        MockSettings settings = withSettings().name("my list");66        List mock = mock(List.class, settings);67        Set mock2 = mock(Set.class);68        // then69        verify(listener).onMockCreated(eq(mock), any(MockCreationSettings.class));70        verify(listener).onMockCreated(eq(mock2), any(MockCreationSettings.class));71        verifyNoMoreInteractions(listener);72    }73    @SuppressWarnings({"CheckReturnValue", "MockitoUsage"})74    @Test75    public void removes_creation_listener() {76        // given creation listener is added77        MockCreationListener listener = mock(MockCreationListener.class);78        framework.addListener(listener);79        // and hooked up correctly80        mock(List.class);81        verify(listener).onMockCreated(ArgumentMatchers.any(), any(MockCreationSettings.class));82        // when83        framework.removeListener(listener);84        mock(Set.class);85        // then86        verifyNoMoreInteractions(listener);87    }88    @Test89    public void prevents_duplicate_listeners_of_the_same_type() {90        // given creation listener is added91        framework.addListener(new MyListener());92        assertThat(93                        new Runnable() {94                            @Override95                            public void run() {96                                framework.addListener(new MyListener());97                            }98                        })99                .throwsException(RedundantListenerException.class)100                .throwsMessage(101                        "\n"102                                + "Problems adding Mockito listener.\n"103                                + "Listener of type 'MyListener' has already been added and not removed.\n"104                                + "It indicates that previous listener was not removed according to the API.\n"105                                + "When you add a listener, don't forget to remove the listener afterwards:\n"106                                + "  Mockito.framework().removeListener(myListener);\n"107                                + "For more information, see the javadoc for RedundantListenerException class.");108    }109    @Test110    public void clearing_all_mocks_is_safe_regardless_of_mock_maker_type() {111        List mock = mock(List.class);112        // expect113        assertTrue(mockingDetails(mock).isMock());114        framework.clearInlineMocks();115    }116    @Test117    public void clears_all_mocks() {118        // clearing mocks only works with inline mocking119        assumeTrue(Plugins.getMockMaker() instanceof InlineMockMaker);120        // given121        List list1 = mock(List.class);122        assertTrue(mockingDetails(list1).isMock());123        List list2 = mock(List.class);124        assertTrue(mockingDetails(list2).isMock());125        // when126        framework.clearInlineMocks();127        // then128        assertFalse(mockingDetails(list1).isMock());129        assertFalse(mockingDetails(list2).isMock());130    }131    @Test132    public void clears_mock() {133        // clearing mocks only works with inline mocking134        assumeTrue(Plugins.getMockMaker() instanceof InlineMockMaker);135        // given136        List list1 = mock(List.class);137        assertTrue(mockingDetails(list1).isMock());138        List list2 = mock(List.class);139        assertTrue(mockingDetails(list2).isMock());140        // when141        framework.clearInlineMock(list1);142        // then143        assertFalse(mockingDetails(list1).isMock());144        assertTrue(mockingDetails(list2).isMock());145    }146    private static class MyListener implements MockitoListener {}147}...Source:MockitoFramework.java  
...8import org.mockito.invocation.InvocationFactory;9import org.mockito.listeners.MockitoListener;10import org.mockito.plugins.MockitoPlugins;11/**12 * Mockito framework settings and lifecycle listeners, for advanced users or for integrating with other frameworks.13 * <p>14 * To get <code>MockitoFramework</code> instance use {@link Mockito#framework()}.15 * <p>16 * For more info on listeners see {@link #addListener(MockitoListener)}.17 *18 * @since 2.1.019 */20@NotExtensible21public interface MockitoFramework {22    /**23     * Adds listener to Mockito.24     * For a list of supported listeners, see the interfaces that extend {@link MockitoListener}.25     * <p>26     * Listeners can be useful for engs that extend Mockito framework.27     * They are used in the implementation of unused stubbings warnings ({@link org.mockito.quality.MockitoHint}).28     * <p>29     * Make sure you remove the listener when the job is complete, see {@link #removeListener(MockitoListener)}.30     * Currently the listeners list is thread local so you need to remove listener from the same thread otherwise31     * remove is ineffectual.32     * In typical scenarios, it is not a problem, because adding & removing listeners typically happens in the same thread.33     * <p>34     * If you are trying to add the listener but a listener of the same type was already added (and not removed)35     * this method will throw {@link RedundantListenerException}.36     * This is a safeguard to ensure users actually remove the listeners via {@link #removeListener(MockitoListener)}.37     * We do not anticipate the use case where adding the same listener type multiple times is useful.38     * If this safeguard is problematic, please contact us via Mockito issue tracker.39     * <p>40     * For usage examples, see Mockito codebase.41     * If you have ideas and feature requests about Mockito listeners API42     * we are very happy to hear about it via our issue tracker or mailing list.43     *44     * <pre class="code"><code class="java">45     *   Mockito.framework().addListener(myListener);46     * </code></pre>47     *48     * @param listener to add to Mockito49     * @return this instance of mockito framework (fluent builder pattern)50     * @since 2.1.051     */52    MockitoFramework addListener(MockitoListener listener) throws RedundantListenerException;53    /**54     * When you add listener using {@link #addListener(MockitoListener)} make sure to remove it.55     * Currently the listeners list is thread local so you need to remove listener from the same thread otherwise56     * remove is ineffectual.57     * In typical scenarios, it is not a problem, because adding & removing listeners typically happens in the same thread.58     * <p>59     * For usage examples, see Mockito codebase.60     * If you have ideas and feature requests about Mockito listeners API61     * we are very happy to hear about it via our issue tracker or mailing list.62     *63     * @param listener to remove64     * @return this instance of mockito framework (fluent builder pattern)65     * @since 2.1.066     */67    MockitoFramework removeListener(MockitoListener listener);68    /**69     * Returns an object that has access to Mockito plugins.70     * An example plugin is {@link org.mockito.plugins.MockMaker}.71     * For information why and how to use this method see {@link MockitoPlugins}.72     *73     * @return object that gives access to mockito plugins74     * @since 2.10.075     */76    MockitoPlugins getPlugins();77    /**78     * Returns a factory that can create instances of {@link Invocation}.79     * It is useful for framework integrations, because {@link Invocation} is {@link NotExtensible}.80     *81     * @return object that can construct invocations82     * @since 2.10.083     */84    InvocationFactory getInvocationFactory();85    /**86     * Clears up internal state of all inline mocks.87     * This method is only meaningful if inline mock maker is in use.88     * Otherwise this method is a no-op and need not be used.89     * <p>90     * This method is useful to tackle subtle memory leaks that are possible due to the nature of inline mocking91     * (issue <a href="https://github.com/mockito/mockito/pull/1619">#1619</a>).92     * If you are facing those problems, call this method at the end of the test (or in "@After" method).93     * See examples of using "clearInlineMocks" in Mockito test code.94     * To find out why inline mock maker keeps track of the mock objects see {@link org.mockito.plugins.InlineMockMaker}.95     * <p>96     * Mockito's "inline mocking" enables mocking final types, enums and final methods97     * (read more in section 39 of {@link Mockito} javadoc).98     * This method is only meaningful when {@link org.mockito.plugins.InlineMockMaker} is in use.99     * If you're using a different {@link org.mockito.plugins.MockMaker} then this method is a no-op.100     *101     * <pre class="code"><code class="java">102     * public class ExampleTest {103     *104     *     @After105     *     public void clearMocks() {106     *         Mockito.framework().clearInlineMocks();107     *     }108     *109     *     @Test110     *     public void someTest() {111     *         ...112     *     }113     * }114     * </pre>115     *116     * If you have feedback or a better idea how to solve the problem please reach out.117     *118     * @since 2.25.0119     * @see #clearInlineMock(Object)120     */...Source:DefaultInternalRunner.java  
...36                            @Override37                            public void evaluate() throws Throwable {38                                AutoCloseable closeable;39                                if (mockitoTestListener == null) {40                                    // get new test listener and add it to the framework41                                    mockitoTestListener = listenerSupplier.get();42                                    Mockito.framework().addListener(mockitoTestListener);43                                    // init annotated mocks before tests44                                    closeable = MockitoAnnotations.openMocks(target);45                                } else {46                                    closeable = null;47                                }48                                try {49                                    base.evaluate();50                                } finally {51                                    if (closeable != null) {52                                        closeable.close();53                                    }54                                }55                            }56                        };57                    }58                    public void run(final RunNotifier notifier) {59                        RunListener listener =60                                new RunListener() {61                                    Throwable failure;62                                    @Override63                                    public void testFailure(Failure failure) throws Exception {64                                        this.failure = failure.getException();65                                    }66                                    @Override67                                    public void testFinished(Description description)68                                            throws Exception {69                                        try {70                                            if (mockitoTestListener != null) {71                                                Mockito.framework()72                                                        .removeListener(mockitoTestListener);73                                                mockitoTestListener.testFinished(74                                                        new DefaultTestFinishedEvent(75                                                                target,76                                                                description.getMethodName(),77                                                                failure));78                                                mockitoTestListener = null;79                                            }80                                            Mockito.validateMockitoUsage();81                                        } catch (Throwable t) {82                                            // In order to produce clean exception to the user we83                                            // need to fire test failure with the right description84                                            // Otherwise JUnit framework will report failure with85                                            // some generic test name86                                            notifier.fireTestFailure(new Failure(description, t));87                                        }88                                    }89                                };90                        notifier.addListener(listener);91                        super.run(notifier);92                    }93                };94    }95    @Override96    public void run(final RunNotifier notifier) {97        runner.run(notifier);98    }...Source:MockTracker.java  
...24import java.lang.reflect.Field;25import java.util.IdentityHashMap;26/**27 * An util class used to track mock creation, and reset them when closing. Note only one instance is28 * allowed at anytime, as Mockito framework throws exception if there is already a listener of the29 * same type registered.30 */31public class MockTracker implements MockCreationListener, AutoCloseable {32    private static final String TAG = MockTracker.class.getSimpleName();33    private static final Field SPIED_INSTANCE_FIELD;34    static {35        try {36            SPIED_INSTANCE_FIELD = CreationSettings.class.getDeclaredField("spiedInstance");37            SPIED_INSTANCE_FIELD.setAccessible(true);38        } catch (NoSuchFieldException e) {39            throw new RuntimeException(e);40        }41    }42    private final MockitoFramework mMockitoFramework = Mockito.framework();43    private final IdentityHashMap<Object, Void> mMocks = new IdentityHashMap<>();44    public MockTracker() {45        mMockitoFramework.addListener(this);46    }47    public void stopTracking() {48        mMockitoFramework.removeListener(this);49    }50    @Override51    public void onMockCreated(Object mock, MockCreationSettings settings) {52        mMocks.put(mock, null);53        clearSpiedInstanceIfNeeded(mock, settings);54    }55    // HACK: Changing Mockito core implementation details.56    // TODO(b/123984854): Remove this once there is a real fix....Source:DefaultMockitoFramework.java  
1/*2 * Copyright (c) 2016 Mockito contributors3 * This program is made available under the terms of the MIT License.4 */5package org.mockito.internal.framework;6import static org.mockito.internal.progress.ThreadSafeMockingProgress.mockingProgress;7import org.mockito.MockitoFramework;8import org.mockito.internal.configuration.plugins.Plugins;9import org.mockito.internal.invocation.DefaultInvocationFactory;10import org.mockito.internal.util.Checks;11import org.mockito.invocation.InvocationFactory;12import org.mockito.listeners.MockitoListener;13import org.mockito.plugins.InlineMockMaker;14import org.mockito.plugins.MockMaker;15import org.mockito.plugins.MockitoPlugins;16public class DefaultMockitoFramework implements MockitoFramework {17    @Override18    public MockitoFramework addListener(MockitoListener listener) {19        Checks.checkNotNull(listener, "listener");...framework
Using AI Code Generation
1import static org.mockito.Mockito.*;2import org.mockito.Mock;3import org.mockito.MockitoAnnotations;4import org.mockito.runners.MockitoJUnitRunner;5import org.junit.Before;6import org.junit.Test;7import org.junit.runner.RunWith;8import org.mockito.ArgumentCaptor;9import org.mockito.Captor;10import org.mockito.InjectMocks;11import org.mockito.Spy;12import org.mockito.invocation.InvocationOnMock;13import org.mockito.stubbing.Answer;14import static org.junit.Assert.*;15public class Test1 {16    private List mockedList;17    public void test1() {18        mockedList.add("one");19        mockedList.clear();20        verify(mockedList).add("one");21        verify(mockedList).clear();22    }23}24import static org.mockito.Mockito.*;25import org.mockito.Mock;26import org.mockito.MockitoAnnotations;27import org.mockito.runners.MockitoJUnitRunner;28import org.junit.Before;29import org.junit.Test;30import org.junit.runner.RunWith;31import org.mockito.ArgumentCaptor;32import org.mockito.Captor;33import org.mockito.InjectMocks;34import org.mockito.Spy;35import org.mockito.invocation.InvocationOnMock;36import org.mockito.stubbing.Answer;37import static org.junit.Assert.*;38public class Test2 {39    private List mockedList;40    public void test2() {41        when(mockedList.get(0)).thenReturn("first");42        when(mockedList.get(1)).thenThrow(new RuntimeException());43        assertEquals("first", mockedList.get(0));44        assertEquals(null, mockedList.get(999));45        verify(mockedList).get(0);46    }47}48import static org.mockito.Mockito.*;49import org.mockito.Mock;50import org.mockito.MockitoAnnotations;51import org.mockito.runners.MockitoJUnitRunner;52import org.junit.Before;53import org.junit.Test;54import org.junit.runner.RunWith;55import org.mockito.ArgumentCaptor;56import org.mockito.Captor;57import org.mockito.InjectMocks;58import org.mockito.Spy;59import org.mockito.invocation.InvocationOnMock;60import org.mockito.stubbing.Answer;61import static org.junit.Assert.*;62public class Test3 {63    private List mockedList;64    public void test3() {65        when(mockedList.get(anyInt())).thenReturn("element");66        assertEquals("element", mockedList.get(999));framework
Using AI Code Generation
1package com.ack.j2se.mock;2import org.junit.Test;3import org.junit.runner.RunWith;4import org.mockito.Mock;5import org.mockito.runners.MockitoJUnitRunner;6import static org.mockito.Mockito.when;7import static org.mockito.Mockito.verify;8@RunWith(MockitoJUnitRunner.class)9public class MockitoTest {10  private Collaborator collaborator;11  public void test() {12    when(collaborator.doSomething()).thenReturn("Hello World");13    Producer producer = new Producer(collaborator);14    producer.produce();15    verify(collaborator).doSomething();16  }17}18package com.ack.j2se.mock;19public class Producer {20  private Collaborator collaborator;21  public Producer(Collaborator collaborator) {22    this.collaborator = collaborator;23  }24  public void produce() {25    collaborator.doSomething();26  }27}28package com.ack.j2se.mock;29public interface Collaborator {30  String doSomething();31}32package com.ack.j2se.mock;33public class CollaboratorImpl implements Collaborator {34  public String doSomething() {35    return "Hello World";36  }37}38package com.ack.j2se.mock;39public class CollaboratorImpl2 implements Collaborator {40  public String doSomething() {41    return "Hello World 2";42  }43}44package com.ack.j2se.mock;45import org.junit.Test;46import org.junit.runner.RunWith;47import org.mockito.Mock;48import org.mockito.runners.MockitoJUnitRunner;49import static org.mockito.Mockito.when;50import static org.mockito.Mockito.verify;51@RunWith(MockitoJUnitRunner.class)52public class MockitoTest2 {53  private Collaborator collaborator;54  public void test() {55    when(collaborator.doSomething()).thenReturn("Hello World");56    Producer producer = new Producer(collaborator);57    producer.produce();58    verify(collaborator).doSomething();59  }60}61package com.ack.j2se.mock;62import org.junit.Test;63import org.junit.runner.RunWith;64import org.mockito.Mock;65import org.mockito.runners.MockitoJUnitRunner;66import static org.mockito.Mockito.when;67import static org.mockito.Mockito.verify;68@RunWith(MockitoJUnitRunner.class)69public class MockitoTest3 {framework
Using AI Code Generation
1import org.mockito.Mockito;2import org.mockito.Mock;3import org.mockito.MockitoAnnotations;4import org.mockito.InjectMocks;5import org.junit.Before;6import org.junit.Test;7import static org.junit.Assert.*;8import static org.mockito.Mockito.when;9import static org.mockito.Mockito.verify;10import static org.mockito.Mockito.times;11import static org.mockito.Mockito.anyString;12import static org.mockito.Mockito.doNothing;13import static org.mockito.Mockito.doThrow;14import static org.mockito.Mockito.spy;15import static org.mockito.Mockito.doReturn;16import static org.mockito.Mockito.doCallRealMethod;17import static org.mockito.Mockito.doAnswer;18import static org.mockito.Mockito.doNothing;19import static org.mockito.Mockito.doThrow;20import static org.mockito.Mockito.verify;21import static org.mockito.Mockito.times;22import static org.mockito.Mockito.anyString;23import static org.mockito.Mockito.doNothing;24import static org.mockito.Mockito.doThrow;25import static org.mockito.Mockito.spy;26import static org.mockito.Mockito.doReturn;27import static org.mockito.Mockito.doCallRealMethod;28import static org.mockito.Mockito.doAnswer;29import static org.mockito.Mockito.doNothing;30import static org.mockito.Mockito.doThrow;31import static org.mockito.Mockito.verify;32import static org.mockito.Mockito.times;33import static org.mockito.Mockito.anyString;34import static org.mockito.Mockito.doNothing;35import static org.mockito.Mockito.doThrow;36import static org.mockito.Mockito.spy;37import static org.mockito.Mockito.doReturn;38import static org.mockito.Mockito.doCallRealMethod;39import static org.mockito.Mockito.doAnswer;40import static org.mockito.Mockito.doNothing;41import static org.mockito.Mockito.doThrow;42import static org.mockito.Mockito.verify;43import static org.mockito.Mockito.times;44import static org.mockito.Mockito.anyString;45import static org.mockito.Mockito.doNothing;46import static org.mockito.Mockito.doThrow;47import static org.mockito.Mockito.spy;48import static org.mockito.Mockito.doReturn;49import static org.mockito.Mockito.doCallRealMethod;50import static org.mockito.Mockito.doAnswer;51import static org.mockito.Mockito.doNothing;52import static org.mockito.Mockito.doThrow;53import static org.mockito.Mockito.verify;54import static org.mockito.Mockito.times;55import static org.mockito.Mockito.anyString;56import static org.mockito.Mockito.doNothing;57import static org.mockito.Mockito.doThrow;58import static org.mockito.Mockito.spy;59import static org.mockito.Mockito.doReturn;60import static org.mockito.Mockito.doCallRealMethod;61import static org.mockito.Mockito.doAnswer;62import static org.mockito.Mockito.doNothing;63import static org.mockito.Mockito.doThrow;64import static org.mockito.Mockito.verify;65import static org.mockito.Mockito.times;66import static org.mockitoframework
Using AI Code Generation
1package com.ack.j2se.mocking;2import org.junit.Test;3import java.util.List;4import static org.mockito.Mockito.mock;5import static org.mockito.Mockito.verify;6public class MockitoFrameworkTest {7  public void testMocking() {8    List mockedList = mock( List.class );9    mockedList.add( "one" );10    mockedList.clear();11    verify( mockedList ).add( "one" );12    verify( mockedList ).clear();13  }14}15BUILD SUCCESSFUL (total time: 1 second)16List mockedList = mock( List.class );17mockedList.add( "one" );18mockedList.clear();19verify( mockedList ).add( "one" );20verify( mockedList ).clear();21verify( mockedList, times( 2 ) ).add( "one" );framework
Using AI Code Generation
1package test;2import org.junit.Test;3import static org.mockito.Mockito.*;4import org.mockito.Mockito;5import org.mockito.MockitoAnnotations;6import org.mockito.InjectMocks;7import org.mockito.Mock;8import org.mockito.Spy;9import org.mockito.MockitoAnnotations.Mock;10import org.mockito.MockitoAnnotations.Spy;11public class MockitoTest {12    private Dependency dependency;13    private SystemUnderTest systemUnderTest;14    private Dependency dependencySpy;15    public void setUp() {16        MockitoAnnotations.initMocks(this);17    }18    public void test() {19        when(dependency.retrieveAllStats()).thenReturn(new int[] {1,2,3});20        assertEquals(6, systemUnderTest.methodCallingADataService());21    }22    public void test2() {23        when(dependency.retrieveAllStats()).thenReturn(new int[] {1,2,3});24        assertEquals(6, systemUnderTest.methodCallingADataService());25    }26}27package test;28public class Dependency {29    public int[] retrieveAllStats() {30        return new int[] {1,2,3};31    }32}33package test;34public class SystemUnderTest {35    private Dependency dependency;36    public int methodCallingADataService() {37        int[] stats = dependency.retrieveAllStats();38        int sum = 0;39        for(int stat : stats) {40            sum += stat;41        }42        return sum;43    }44}framework
Using AI Code Generation
1package com.ack.j2se.mock;2import java.util.List;3import static org.mockito.Mockito.*;4public class MockitoMockUsingFrameworkMethod {5  public static void main( String[] args ) {6    List mockedList = mock( List.class );7    mockedList.add( "one" );8    mockedList.clear();9    verify( mockedList ).add( "one" );10    verify( mockedList ).clear();11  }12}13-> at com.ack.j2se.mock.MockitoMockUsingFrameworkMethod.main(MockitoMockUsingFrameworkMethod.java:13)14-> at com.ack.j2se.mock.MockitoMockUsingFrameworkMethod.main(MockitoMockUsingFrameworkMethod.java:12)15    someMethod(anyObject(), "raw String");16    someMethod(anyObject(), eq("String by matcher"));17at com.ack.j2se.mock.MockitoMockUsingFrameworkMethod.main(MockitoMockUsingFrameworkMethod.java:13)framework
Using AI Code Generation
1import org.mockito.Mockito;2import static org.mockito.Mockito.*;3import java.util.*;4import java.io.*;5import java.lang.reflect.*;6import java.net.*;7import java.util.concurrent.*;8import java.util.regex.*;9import java.util.stream.*;10import java.util.function.*;11import java.util.concurrent.atomic.*;12import java.util.concurrent.locks.*;13import java.util.concurrent.atomic.AtomicInteger;14import java.util.concurrent.atomic.AtomicLong;15import java.util.concurrent.atomic.AtomicReference;16import java.util.concurrent.atomic.AtomicReferenceArray;17import java.util.concurrent.atomic.AtomicReferenceFieldUpdater;18import java.util.concurrent.atomic.AtomicIntegerFieldUpdater;19import java.util.concurrent.atomic.AtomicLongFieldUpdater;20import java.util.concurrent.atomic.DoubleAccumulator;21import java.util.concurrent.atomic.DoubleAdder;22import java.util.concurrent.atomic.LongAccumulator;23import java.util.concurrent.atomic.LongAdder;24import java.util.concurrent.locks.AbstractQueuedSynchronizer;25import java.util.concurrent.locks.Condition;26import java.util.concurrent.locks.Lock;27import java.util.concurrent.locks.ReentrantLock;28import java.util.concurrent.locks.ReentrantReadWriteLock;29import java.util.concurrent.locks.StampedLock;30import java.util.concurrent.locks.ReadWriteLock;31import java.util.concurrent.locks.LockSupport;32import java.util.concurrent.locks.ReentrantReadWriteLock.ReadLock;33import java.util.concurrent.locks.ReentrantReadWriteLock.WriteLock;34import java.util.concurrent.locks.AbstractOwnableSynchronizer;35import java.util.concurrent.locks.ReentrantLock;36import java.util.concurrent.locks.ReentrantReadWriteLock;37import java.util.concurrent.locks.StampedLock;38import java.util.concurrent.locks.LockSupport;39import java.util.function.*;40import java.util.function.IntBinaryOperator;41import java.util.function.IntConsumer;42import java.util.function.IntFunction;43import java.util.function.IntPredicate;44import java.util.function.IntSupplier;45import java.util.function.IntToDoubleFunction;46import java.util.function.IntToLongFunction;47import java.util.function.IntUnaryOperator;48import java.util.function.LongBinaryOperator;49import java.util.function.LongConsumer;50import java.util.function.LongFunction;51import java.util.function.LongPredicate;52import java.util.function.LongSupplier;53import java.util.function.LongToDoubleFunction;54import java.util.function.LongToIntFunction;55import java.util.function.LongUnaryOperator;56import java.util.function.DoubleBinaryOperator;57import java.util.function.DoubleConsumer;58import java.util.function.DoubleFunction;59import java.util.function.DoublePredicate;60import java.util.function.DoubleSupplier;61import java.util.function.DoubleToIntFunction;62import java.util.function.DoubleToLongframework
Using AI Code Generation
1import org.mockito.Mockito;2public class 1 {3    public static void main(String[] args) {4        MyInterface myInterface = Mockito.mock(MyInterface.class);5        System.out.println(myInterface.myMethod());6    }7}8import org.mockito.Mockito;9public class 2 {10    public static void main(String[] args) {11        MyInterface myInterface = Mockito.mock(MyInterface.class);12        Mockito.when(myInterface.myMethod()).thenReturn("Hello World");13        System.out.println(myInterface.myMethod());14    }15}16import org.mockito.Mockito;17public class 3 {18    public static void main(String[] args) {19        MyInterface myInterface = Mockito.mock(MyInterface.class);20        Mockito.when(myInterface.myMethod()).thenReturn("Hello World");21        System.out.println(myInterface.myMethod());22    }23}framework
Using AI Code Generation
1package com.mockitotest;2import static org.mockito.Mockito.when;3import org.junit.Test;4import org.junit.runner.RunWith;5import org.mockito.InjectMocks;6import org.mockito.Mock;7import org.mockito.runners.MockitoJUnitRunner;8@RunWith(MockitoJUnitRunner.class)9public class MockitoTest {10	private Service service;11	private ServiceConsumer consumer;12	public void test() {13		when(service.getMessage()).thenReturn("Hello");14		String message = consumer.getMessage();15		System.out.println(message);16	}17}18package com.mockitotest;19import static org.mockito.Mockito.mock;20import static org.mockito.Mockito.when;21import static org.mockito.Mockito.verify;22import org.junit.Test;23public class MockitoTest2 {24	public void test() {25		Service service = mock(Service.class);26		ServiceConsumer consumer = new ServiceConsumer(service);27		when(service.getMessage()).thenReturn("Hello");28		String message = consumer.getMessage();29		System.out.println(message);30		verify(service).getMessage();31	}32}33package com.mockitotest;34import static org.mockito.Mockito.mock;35import static org.mockito.Mockito.when;36import static org.mockito.Mockito.verify;37import org.junit.Test;38public class MockitoTest3 {39	public void test() {40		Service service = mock(Service.class);41		ServiceConsumer consumer = new ServiceConsumer(service);42		when(service.getMessage()).thenReturn("Hello");43		String message = consumer.getMessage();44		System.out.println(message);45		verify(service).getMessage();46	}47}48import java.util.concurrent.locks.StampedLock;49import java.util.concurrent.locks.LockSupport;50import java.util.function.*;51import java.util.function.IntBinaryOperator;52import java.util.function.IntConsumer;53import java.util.function.IntFunction;54import java.util.function.IntPredicate;55import java.util.function.IntSupplier;56import java.util.function.IntToDoubleFunction;57import java.util.function.IntToLongFunction;58import java.util.function.IntUnaryOperator;59import java.util.function.LongBinaryOperator;60import java.util.function.LongConsumer;61import java.util.function.LongFunction;62import java.util.function.LongPredicate;63import java.util.function.LongSupplier;64import java.util.function.LongToDoubleFunction;65import java.util.function.LongToIntFunction;66import java.util.function.LongUnaryOperator;67import java.util.function.DoubleBinaryOperator;68import java.util.function.DoubleConsumer;69import java.util.function.DoubleFunction;70import java.util.function.DoublePredicate;71import java.util.function.DoubleSupplier;72import java.util.function.DoubleToIntFunction;73import java.util.function.DoubleToLongframework
Using AI Code Generation
1import org.mockito.Mockito;2public class 1 {3    public static void main(String[] args) {4        MyInterface myInterface = Mockito.mock(MyInterface.class);5        System.out.println(myInterface.myMethod());6    }7}8import org.mockito.Mockito;9public class 2 {10    public static void main(String[] args) {11        MyInterface myInterface = Mockito.mock(MyInterface.class);12        Mockito.when(myInterface.myMethod()).thenReturn("Hello World");13        System.out.println(myInterface.myMethod());14    }15}16import org.mockito.Mockito;17public class 3 {18    public static void main(String[] args) {19        MyInterface myInterface = Mockito.mock(MyInterface.class);20        Mockito.when(myInterface.myMethod()).thenReturn("Hello World");21        System.out.println(myInterface.myMethod());22    }23}framework
Using AI Code Generation
1package com.mockitotest;2import static org.mockito.Mockito.when;3import org.junit.Test;4import org.junit.runner.RunWith;5import org.mockito.InjectMocks;6import org.mockito.Mock;7import org.mockito.runners.MockitoJUnitRunner;8@RunWith(MockitoJUnitRunner.class)9public class MockitoTest {10	private Service service;11	private ServiceConsumer consumer;12	public void test() {13		when(service.getMessage()).thenReturn("Hello");14		String message = consumer.getMessage();15		System.out.println(message);16	}17}18package com.mockitotest;19import static org.mockito.Mockito.mock;20import static org.mockito.Mockito.when;21import static org.mockito.Mockito.verify;22import org.junit.Test;23public class MockitoTest2 {24	public void test() {25		Service service = mock(Service.class);26		ServiceConsumer consumer = new ServiceConsumer(service);27		when(service.getMessage()).thenReturn("Hello");28		String message = consumer.getMessage();29		System.out.println(message);30		verify(service).getMessage();31	}32}33package com.mockitotest;34import static org.mockito.Mockito.mock;35import static org.mockito.Mockito.when;36import static org.mockito.Mockito.verify;37import org.junit.Test;38public class MockitoTest3 {39	public void test() {40		Service service = mock(Service.class);41		ServiceConsumer consumer = new ServiceConsumer(service);42		when(service.getMessage()).thenReturn("Hello");43		String message = consumer.getMessage();44		System.out.println(message);45		verify(service).getMessage();46	}47}48	}49}50package com.mockitotest;51import static org.mockito.Mockito.mock;52import static org.mockito.Mockito.when;53import static org.mockito.Mockito.verify;54import org.junit.Test;55public class MockitoTest2 {56	public void test() {57		Service service = mock(Service.class);58		ServiceConsumer consumer = new ServiceConsumer(service);59		when(service.getMessage()).thenReturn("Hello");60		String message = consumer.getMessage();61		System.out.println(message);62		verify(service).getMessage();63	}64}65package com.mockitotest;66import static org.mockito.Mockito.mock;67import static org.mockito.Mockito.when;68import static org.mockito.Mockito.verify;69import org.junit.Test;70public class MockitoTest3 {71	public void test() {72		Service service = mock(Service.class);73		ServiceConsumer consumer = new ServiceConsumer(service);74		when(service.getMessage()).thenReturn("Hello");75		String message = consumer.getMessage();76		System.out.println(message);77		verify(service).getMessage();78	}79}framework
Using AI Code Generation
1package com.ack.j2se.mock;2import java.util.List;3import static org.mockito.Mockito.*;4public class MockitoMockUsingFrameworkMethod {5  public static void main( String[] args ) {6    List mockedList = mock( List.class );7    mockedList.add( "one" );8    mockedList.clear();9    verify( mockedList ).add( "one" );10    verify( mockedList ).clear();11  }12}13-> at com.ack.j2se.mock.MockitoMockUsingFrameworkMethod.main(MockitoMockUsingFrameworkMethod.java:13)14-> at com.ack.j2se.mock.MockitoMockUsingFrameworkMethod.main(MockitoMockUsingFrameworkMethod.java:12)15    someMethod(anyObject(), "raw String");16    someMethod(anyObject(), eq("String by matcher"));17at com.ack.j2se.mock.MockitoMockUsingFrameworkMethod.main(MockitoMockUsingFrameworkMethod.java:13)framework
Using AI Code Generation
1package com.mockitotest;2import static org.mockito.Mockito.when;3import org.junit.Test;4import org.junit.runner.RunWith;5import org.mockito.InjectMocks;6import org.mockito.Mock;7import org.mockito.runners.MockitoJUnitRunner;8@RunWith(MockitoJUnitRunner.class)9public class MockitoTest {10	private Service service;11	private ServiceConsumer consumer;12	public void test() {13		when(service.getMessage()).thenReturn("Hello");14		String message = consumer.getMessage();15		System.out.println(message);16	}17}18package com.mockitotest;19import static org.mockito.Mockito.mock;20import static org.mockito.Mockito.when;21import static org.mockito.Mockito.verify;22import org.junit.Test;23public class MockitoTest2 {24	public void test() {25		Service service = mock(Service.class);26		ServiceConsumer consumer = new ServiceConsumer(service);27		when(service.getMessage()).thenReturn("Hello");28		String message = consumer.getMessage();29		System.out.println(message);30		verify(service).getMessage();31	}32}33package com.mockitotest;34import static org.mockito.Mockito.mock;35import static org.mockito.Mockito.when;36import static org.mockito.Mockito.verify;37import org.junit.Test;38public class MockitoTest3 {39	public void test() {40		Service service = mock(Service.class);41		ServiceConsumer consumer = new ServiceConsumer(service);42		when(service.getMessage()).thenReturn("Hello");43		String message = consumer.getMessage();44		System.out.println(message);45		verify(service).getMessage();46	}47}Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!
