Best Mockito code snippet using org.mockito.internal.util.reflection.InstrumentationMemberAccessor.assureArguments
Source:InstrumentationMemberAccessor.java  
...147        if (Modifier.isAbstract(constructor.getDeclaringClass().getModifiers())) {148            throw new InstantiationException(149                    "Cannot instantiate abstract " + constructor.getDeclaringClass().getTypeName());150        }151        assureArguments(constructor, null, null, arguments, constructor.getParameterTypes());152        try {153            Object module =154                    DISPATCHER.invokeWithArguments(155                            getModule.bindTo(constructor.getDeclaringClass()));156            String packageName = constructor.getDeclaringClass().getPackage().getName();157            assureOpen(module, packageName);158            MethodHandle handle =159                    ((MethodHandles.Lookup)160                                    DISPATCHER.invokeWithArguments(161                                            privateLookupIn,162                                            constructor.getDeclaringClass(),163                                            DISPATCHER.getLookup()))164                            .unreflectConstructor(constructor);165            AtomicBoolean thrown = new AtomicBoolean();166            Object value =167                    onConstruction.invoke(168                            () -> {169                                try {170                                    return DISPATCHER.invokeWithArguments(handle, arguments);171                                } catch (Throwable throwable) {172                                    thrown.set(true);173                                    return throwable;174                                }175                            });176            if (thrown.get()) {177                throw new InvocationTargetException((Throwable) value);178            } else {179                return value;180            }181        } catch (InvocationTargetException e) {182            throw e;183        } catch (Throwable t) {184            throw new IllegalStateException(185                    "Could not construct "186                            + constructor187                            + " with arguments "188                            + Arrays.toString(arguments),189                    t);190        }191    }192    @Override193    public Object invoke(Method method, Object target, Object... arguments)194            throws InvocationTargetException {195        assureArguments(196                method,197                Modifier.isStatic(method.getModifiers()) ? null : target,198                method.getDeclaringClass(),199                arguments,200                method.getParameterTypes());201        try {202            Object module =203                    DISPATCHER.invokeWithArguments(getModule.bindTo(method.getDeclaringClass()));204            String packageName = method.getDeclaringClass().getPackage().getName();205            assureOpen(module, packageName);206            MethodHandle handle =207                    ((MethodHandles.Lookup)208                                    DISPATCHER.invokeWithArguments(209                                            privateLookupIn,210                                            method.getDeclaringClass(),211                                            DISPATCHER.getLookup()))212                            .unreflect(method);213            if (!Modifier.isStatic(method.getModifiers())) {214                handle = handle.bindTo(target);215            }216            try {217                return DISPATCHER.invokeWithArguments(handle, arguments);218            } catch (Throwable t) {219                throw new InvocationTargetException(t);220            }221        } catch (InvocationTargetException e) {222            throw e;223        } catch (Throwable t) {224            throw new IllegalStateException(225                    "Could not invoke "226                            + method227                            + " on "228                            + target229                            + " with arguments "230                            + Arrays.toString(arguments),231                    t);232        }233    }234    @Override235    public Object get(Field field, Object target) {236        assureArguments(237                field,238                Modifier.isStatic(field.getModifiers()) ? null : target,239                field.getDeclaringClass(),240                new Object[0],241                new Class<?>[0]);242        try {243            Object module =244                    DISPATCHER.invokeWithArguments(getModule.bindTo(field.getDeclaringClass()));245            String packageName = field.getDeclaringClass().getPackage().getName();246            assureOpen(module, packageName);247            MethodHandle handle =248                    ((MethodHandles.Lookup)249                                    DISPATCHER.invokeWithArguments(250                                            privateLookupIn,251                                            field.getDeclaringClass(),252                                            DISPATCHER.getLookup()))253                            .unreflectGetter(field);254            if (!Modifier.isStatic(field.getModifiers())) {255                handle = handle.bindTo(target);256            }257            return DISPATCHER.invokeWithArguments(handle);258        } catch (Throwable t) {259            throw new IllegalStateException("Could not read " + field + " on " + target, t);260        }261    }262    @Override263    public void set(Field field, Object target, Object value) throws IllegalAccessException {264        assureArguments(265                field,266                Modifier.isStatic(field.getModifiers()) ? null : target,267                field.getDeclaringClass(),268                new Object[] {value},269                new Class<?>[] {field.getType()});270        boolean illegalAccess = false;271        try {272            Object module =273                    DISPATCHER.invokeWithArguments(getModule.bindTo(field.getDeclaringClass()));274            String packageName = field.getDeclaringClass().getPackage().getName();275            assureOpen(module, packageName);276            // Method handles do not allow setting final fields where setAccessible(true)277            // is required before unreflecting.278            boolean isFinal;279            if (Modifier.isFinal(field.getModifiers())) {280                isFinal = true;281                try {282                    DISPATCHER.setAccessible(field, true);283                } catch (Throwable ignored) {284                    illegalAccess =285                            true; // To distinguish from propagated illegal access exception.286                    throw new IllegalAccessException(287                            "Could not make final field " + field + " accessible");288                }289            } else {290                isFinal = false;291            }292            try {293                MethodHandle handle =294                        ((MethodHandles.Lookup)295                                        DISPATCHER.invokeWithArguments(296                                                privateLookupIn,297                                                field.getDeclaringClass(),298                                                DISPATCHER.getLookup()))299                                .unreflectSetter(field);300                if (!Modifier.isStatic(field.getModifiers())) {301                    handle = handle.bindTo(target);302                }303                DISPATCHER.invokeWithArguments(handle, value);304            } finally {305                if (isFinal) {306                    DISPATCHER.setAccessible(field, false);307                }308            }309        } catch (Throwable t) {310            if (illegalAccess) {311                throw (IllegalAccessException) t;312            } else {313                throw new IllegalStateException("Could not read " + field + " on " + target, t);314            }315        }316    }317    private void assureOpen(Object module, String packageName) throws Throwable {318        // It would be more reliable to check if a module's package already is opened to319        // the dispatcher module from before. Unfortunately, there is no reliable check320        // for doing so since the isOpen(String, Module) method always returns true321        // if the second argument is an unnamed module. Therefore, for now, we need322        // to reopen packages even if they are already opened to the dispatcher module.323        if (!(Boolean) DISPATCHER.invokeWithArguments(isOpen, module, packageName)) {324            DISPATCHER.invokeWithArguments(325                    redefineModule.bindTo(INSTRUMENTATION),326                    module,327                    Collections.emptySet(),328                    Collections.emptyMap(),329                    Collections.singletonMap(330                            packageName, Collections.singleton(DISPATCHER.getModule())),331                    Collections.emptySet(),332                    Collections.emptyMap());333        }334    }335    private static void assureArguments(336            AccessibleObject target,337            Object owner,338            Class<?> type,339            Object[] values,340            Class<?>[] types) {341        if (owner != null) {342            if (!type.isAssignableFrom(owner.getClass())) {343                throw new IllegalArgumentException("Cannot access " + target + " on " + owner);344            }345        }346        if (types.length != values.length) {347            throw new IllegalArgumentException(348                    "Incorrect number of arguments for "349                            + target...assureArguments
Using AI Code Generation
1public void testAssureArguments() {2    MemberAccessor memberAccessor = new InstrumentationMemberAccessor();3    memberAccessor.assureArguments("test", new Class[]{String.class}, new Object[]{"test"});4}5java.lang.IllegalArgumentException: Argument(s) are not valid for this method:6	at org.mockito.internal.util.reflection.InstrumentationMemberAccessor.assureArguments(InstrumentationMemberAccessor.java:86)7	at org.mockito.internal.util.reflection.InstrumentationMemberAccessor.assureArguments(InstrumentationMemberAccessor.java:69)8	at com.mockitotutorial.MockitoTutorial.testAssureArguments(MockitoTutorial.java:68)9	at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)10	at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)11	at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)12	at java.lang.reflect.Method.invoke(Method.java:498)13	at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:50)14	at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)15	at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47)16	at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)17	at org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:26)18	at org.junit.internal.runners.statements.RunAfters.evaluate(RunAfters.java:27)19	at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325)20	at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:78)21	at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:57)22	at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)23	at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)24	at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)25	at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)26	at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)27	at org.junit.runners.ParentRunner.run(ParentRunner.java:363)28	at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:86)29	at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38)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!!
