How to use method of org.mockito.internal.creation.bytebuddy.InlineDelegateByteBuddyMockMakerTest class

Best Mockito code snippet using org.mockito.internal.creation.bytebuddy.InlineDelegateByteBuddyMockMakerTest.

Run Mockito automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

copy
1/*
2 * Copyright (c) 2017 Mockito contributors
3 * This program is made available under the terms of the MIT License.
4 */
5package org.mockito.internal.creation.bytebuddy;
6
7import static net.bytebuddy.ClassFileVersion.JAVA_V11;
8import static net.bytebuddy.ClassFileVersion.JAVA_V8;
9import static net.bytebuddy.matcher.ElementMatchers.named;
10import static org.assertj.core.api.Assertions.assertThat;
11import static org.assertj.core.api.Assertions.fail;
12import static org.junit.Assert.assertEquals;
13import static org.junit.Assert.assertNotNull;
14import static org.junit.Assume.assumeTrue;
15
16import java.io.IOException;
17import java.util.HashMap;
18import java.util.List;
19import java.util.Observable;
20import java.util.Observer;
21import java.util.Optional;
22import java.util.Set;
23import java.util.concurrent.Callable;
24import java.util.regex.Pattern;
25
26import net.bytebuddy.ByteBuddy;
27import net.bytebuddy.ClassFileVersion;
28import net.bytebuddy.description.modifier.Visibility;
29import net.bytebuddy.description.type.TypeDescription;
30import net.bytebuddy.implementation.FixedValue;
31import net.bytebuddy.implementation.StubMethod;
32import net.bytebuddy.utility.JavaConstant;
33import org.junit.Test;
34import org.mockito.Answers;
35import org.mockito.exceptions.base.MockitoException;
36import org.mockito.internal.creation.MockSettingsImpl;
37import org.mockito.internal.creation.settings.CreationSettings;
38import org.mockito.internal.handler.MockHandlerImpl;
39import org.mockito.internal.stubbing.answers.Returns;
40import org.mockito.internal.util.collections.Sets;
41import org.mockito.mock.MockCreationSettings;
42import org.mockito.mock.SerializableMode;
43import org.mockito.plugins.MockMaker;
44
45public class InlineDelegateByteBuddyMockMakerTest
46        extends AbstractByteBuddyMockMakerTest<InlineByteBuddyMockMaker> {
47
48    public InlineDelegateByteBuddyMockMakerTest() {
49        super(new InlineByteBuddyMockMaker());
50    }
51
52    @Override
53    protected Class<?> mockTypeOf(Class<?> type) {
54        return type;
55    }
56
57    @Test
58    public void should_create_mock_from_final_class() throws Exception {
59        MockCreationSettings<FinalClass> settings = settingsFor(FinalClass.class);
60        FinalClass proxy =
61                mockMaker.createMock(settings, new MockHandlerImpl<FinalClass>(settings));
62        assertThat(proxy.foo()).isEqualTo("bar");
63    }
64
65    @Test
66    public void should_create_mock_from_final_spy() throws Exception {
67        MockCreationSettings<FinalSpy> settings = settingsFor(FinalSpy.class);
68        Optional<FinalSpy> proxy =
69                mockMaker.createSpy(
70                        settings,
71                        new MockHandlerImpl<>(settings),
72                        new FinalSpy("value", true, (byte) 1, (short) 1, (char) 1, 1, 1L, 1f, 1d));
73        assertThat(proxy)
74                .hasValueSatisfying(
75                        spy -> {
76                            assertThat(spy.aString).isEqualTo("value");
77                            assertThat(spy.aBoolean).isTrue();
78                            assertThat(spy.aByte).isEqualTo((byte) 1);
79                            assertThat(spy.aShort).isEqualTo((short) 1);
80                            assertThat(spy.aChar).isEqualTo((char) 1);
81                            assertThat(spy.anInt).isEqualTo(1);
82                            assertThat(spy.aLong).isEqualTo(1L);
83                            assertThat(spy.aFloat).isEqualTo(1f);
84                            assertThat(spy.aDouble).isEqualTo(1d);
85                        });
86    }
87
88    @Test
89    public void should_create_mock_from_non_constructable_class() throws Exception {
90        MockCreationSettings<NonConstructableClass> settings =
91                settingsFor(NonConstructableClass.class);
92        NonConstructableClass proxy =
93                mockMaker.createMock(
94                        settings, new MockHandlerImpl<NonConstructableClass>(settings));
95        assertThat(proxy.foo()).isEqualTo("bar");
96    }
97
98    @Test
99    public void should_create_mock_from_final_class_in_the_JDK() throws Exception {
100        MockCreationSettings<Pattern> settings = settingsFor(Pattern.class);
101        Pattern proxy = mockMaker.createMock(settings, new MockHandlerImpl<Pattern>(settings));
102        assertThat(proxy.pattern()).isEqualTo("bar");
103    }
104
105    @Test
106    public void should_create_mock_from_abstract_class_with_final_method() throws Exception {
107        MockCreationSettings<FinalMethodAbstractType> settings =
108                settingsFor(FinalMethodAbstractType.class);
109        FinalMethodAbstractType proxy =
110                mockMaker.createMock(
111                        settings, new MockHandlerImpl<FinalMethodAbstractType>(settings));
112        assertThat(proxy.foo()).isEqualTo("bar");
113        assertThat(proxy.bar()).isEqualTo("bar");
114    }
115
116    @Test
117    public void should_create_mock_from_final_class_with_interface_methods() throws Exception {
118        MockCreationSettings<FinalMethod> settings =
119                settingsFor(FinalMethod.class, SampleInterface.class);
120        FinalMethod proxy =
121                mockMaker.createMock(settings, new MockHandlerImpl<FinalMethod>(settings));
122        assertThat(proxy.foo()).isEqualTo("bar");
123        assertThat(((SampleInterface) proxy).bar()).isEqualTo("bar");
124    }
125
126    @Test
127    public void should_detect_non_overridden_generic_method_of_supertype() throws Exception {
128        MockCreationSettings<GenericSubClass> settings = settingsFor(GenericSubClass.class);
129        GenericSubClass proxy =
130                mockMaker.createMock(settings, new MockHandlerImpl<GenericSubClass>(settings));
131        assertThat(proxy.value()).isEqualTo("bar");
132    }
133
134    @Test
135    public void should_create_mock_from_hashmap() throws Exception {
136        MockCreationSettings<HashMap> settings = settingsFor(HashMap.class);
137        HashMap proxy = mockMaker.createMock(settings, new MockHandlerImpl<HashMap>(settings));
138        assertThat(proxy.get(null)).isEqualTo("bar");
139    }
140
141    @Test
142    @SuppressWarnings("unchecked")
143    public void should_throw_exception_redefining_unmodifiable_class() {
144        MockCreationSettings settings = settingsFor(int.class);
145        try {
146            mockMaker.createMock(settings, new MockHandlerImpl(settings));
147            fail("Expected a MockitoException");
148        } catch (MockitoException e) {
149            e.printStackTrace();
150            assertThat(e).hasMessageContaining("Could not modify all classes");
151        }
152    }
153
154    @Test
155    @SuppressWarnings("unchecked")
156    public void should_throw_exception_redefining_array() {
157        int[] array = new int[5];
158        MockCreationSettings<? extends int[]> settings = settingsFor(array.getClass());
159        try {
160            mockMaker.createMock(settings, new MockHandlerImpl(settings));
161            fail("Expected a MockitoException");
162        } catch (MockitoException e) {
163            assertThat(e).hasMessageContaining("Arrays cannot be mocked");
164        }
165    }
166
167    @Test
168    public void should_create_mock_from_enum() throws Exception {
169        MockCreationSettings<EnumClass> settings = settingsFor(EnumClass.class);
170        EnumClass proxy = mockMaker.createMock(settings, new MockHandlerImpl<EnumClass>(settings));
171        assertThat(proxy.foo()).isEqualTo("bar");
172    }
173
174    @Test
175    public void should_fail_at_creating_a_mock_of_a_final_class_with_explicit_serialization()
176            throws Exception {
177        MockCreationSettings<FinalClass> settings =
178                new CreationSettings<FinalClass>()
179                        .setTypeToMock(FinalClass.class)
180                        .setSerializableMode(SerializableMode.BASIC);
181
182        try {
183            mockMaker.createMock(settings, new MockHandlerImpl<FinalClass>(settings));
184            fail("Expected a MockitoException");
185        } catch (MockitoException e) {
186            assertThat(e)
187                    .hasMessageContaining("Unsupported settings")
188                    .hasMessageContaining("serialization")
189                    .hasMessageContaining("extra interfaces");
190        }
191    }
192
193    @Test
194    public void should_fail_at_creating_a_mock_of_a_final_class_with_extra_interfaces()
195            throws Exception {
196        MockCreationSettings<FinalClass> settings =
197                new CreationSettings<FinalClass>()
198                        .setTypeToMock(FinalClass.class)
199                        .setExtraInterfaces(Sets.<Class<?>>newSet(List.class));
200
201        try {
202            mockMaker.createMock(settings, new MockHandlerImpl<FinalClass>(settings));
203            fail("Expected a MockitoException");
204        } catch (MockitoException e) {
205            assertThat(e)
206                    .hasMessageContaining("Unsupported settings")
207                    .hasMessageContaining("serialization")
208                    .hasMessageContaining("extra interfaces");
209        }
210    }
211
212    @Test
213    public void should_mock_interface() {
214        MockSettingsImpl<Set> mockSettings = new MockSettingsImpl<Set>();
215        mockSettings.setTypeToMock(Set.class);
216        mockSettings.defaultAnswer(new Returns(10));
217        Set<?> proxy = mockMaker.createMock(mockSettings, new MockHandlerImpl<Set>(mockSettings));
218
219        assertThat(proxy.size()).isEqualTo(10);
220    }
221
222    @Test
223    public void should_mock_interface_to_string() {
224        MockSettingsImpl<Set> mockSettings = new MockSettingsImpl<Set>();
225        mockSettings.setTypeToMock(Set.class);
226        mockSettings.defaultAnswer(new Returns("foo"));
227        Set<?> proxy = mockMaker.createMock(mockSettings, new MockHandlerImpl<Set>(mockSettings));
228
229        assertThat(proxy.toString()).isEqualTo("foo");
230    }
231
232    /**
233     * @see <a href="https://github.com/mockito/mockito/issues/2154">https://github.com/mockito/mockito/issues/2154</a>
234     */
235    @Test
236    public void should_mock_class_to_string() {
237        MockSettingsImpl<Object> mockSettings = new MockSettingsImpl<Object>();
238        mockSettings.setTypeToMock(Object.class);
239        mockSettings.defaultAnswer(new Returns("foo"));
240        Object proxy =
241                mockMaker.createMock(mockSettings, new MockHandlerImpl<Object>(mockSettings));
242
243        assertThat(proxy.toString()).isEqualTo("foo");
244    }
245
246    @Test
247    public void should_leave_causing_stack() throws Exception {
248        MockSettingsImpl<ExceptionThrowingClass> settings = new MockSettingsImpl<>();
249        settings.setTypeToMock(ExceptionThrowingClass.class);
250        settings.defaultAnswer(Answers.CALLS_REAL_METHODS);
251
252        Optional<ExceptionThrowingClass> proxy =
253                mockMaker.createSpy(
254                        settings, new MockHandlerImpl<>(settings), new ExceptionThrowingClass());
255
256        StackTraceElement[] returnedStack = null;
257        try {
258            proxy.get().throwException();
259        } catch (IOException ex) {
260            returnedStack = ex.getStackTrace();
261        }
262
263        assertNotNull("Stack trace from mockito expected", returnedStack);
264
265        assertEquals(ExceptionThrowingClass.class.getName(), returnedStack[0].getClassName());
266        assertEquals("internalThrowException", returnedStack[0].getMethodName());
267    }
268
269    @Test
270    public void should_remove_recursive_self_call_from_stack_trace() throws Exception {
271        StackTraceElement[] stack =
272                new StackTraceElement[] {
273                    new StackTraceElement("foo", "", "", -1),
274                    new StackTraceElement(SampleInterface.class.getName(), "", "", -1),
275                    new StackTraceElement("qux", "", "", -1),
276                    new StackTraceElement("bar", "", "", -1),
277                    new StackTraceElement("baz", "", "", -1)
278                };
279
280        Throwable throwable = new Throwable();
281        throwable.setStackTrace(stack);
282        throwable = MockMethodAdvice.hideRecursiveCall(throwable, 2, SampleInterface.class);
283
284        assertThat(throwable.getStackTrace())
285                .isEqualTo(
286                        new StackTraceElement[] {
287                            new StackTraceElement("foo", "", "", -1),
288                            new StackTraceElement("bar", "", "", -1),
289                            new StackTraceElement("baz", "", "", -1)
290                        });
291    }
292
293    @Test
294    public void should_handle_missing_or_inconsistent_stack_trace() throws Exception {
295        Throwable throwable = new Throwable();
296        throwable.setStackTrace(new StackTraceElement[0]);
297        assertThat(MockMethodAdvice.hideRecursiveCall(throwable, 0, SampleInterface.class))
298                .isSameAs(throwable);
299    }
300
301    @Test
302    public void should_provide_reason_for_wrapper_class() {
303        MockMaker.TypeMockability mockable = mockMaker.isTypeMockable(Integer.class);
304        assertThat(mockable.nonMockableReason())
305                .isEqualTo("Cannot mock wrapper types, String.class or Class.class");
306    }
307
308    @Test
309    public void should_provide_reason_for_vm_unsupported() {
310        MockMaker.TypeMockability mockable = mockMaker.isTypeMockable(int[].class);
311        assertThat(mockable.nonMockableReason())
312                .isEqualTo("VM does not support modification of given type");
313    }
314
315    @Test
316    public void should_mock_method_of_package_private_class() throws Exception {
317        MockCreationSettings<NonPackagePrivateSubClass> settings =
318                settingsFor(NonPackagePrivateSubClass.class);
319        NonPackagePrivateSubClass proxy =
320                mockMaker.createMock(
321                        settings, new MockHandlerImpl<NonPackagePrivateSubClass>(settings));
322        assertThat(proxy.value()).isEqualTo("bar");
323    }
324
325    @Test
326    public void is_type_mockable_excludes_String() {
327        MockMaker.TypeMockability mockable = mockMaker.isTypeMockable(String.class);
328        assertThat(mockable.mockable()).isFalse();
329        assertThat(mockable.nonMockableReason())
330                .contains("Cannot mock wrapper types, String.class or Class.class");
331    }
332
333    @Test
334    public void is_type_mockable_excludes_Class() {
335        MockMaker.TypeMockability mockable = mockMaker.isTypeMockable(Class.class);
336        assertThat(mockable.mockable()).isFalse();
337        assertThat(mockable.nonMockableReason())
338                .contains("Cannot mock wrapper types, String.class or Class.class");
339    }
340
341    @Test
342    public void is_type_mockable_excludes_primitive_classes() {
343        MockMaker.TypeMockability mockable = mockMaker.isTypeMockable(int.class);
344        assertThat(mockable.mockable()).isFalse();
345        assertThat(mockable.nonMockableReason()).contains("primitive");
346    }
347
348    @Test
349    public void is_type_mockable_allows_anonymous() {
350        Observer anonymous =
351                new Observer() {
352                    @Override
353                    public void update(Observable o, Object arg) {}
354                };
355        MockMaker.TypeMockability mockable = mockMaker.isTypeMockable(anonymous.getClass());
356        assertThat(mockable.mockable()).isTrue();
357        assertThat(mockable.nonMockableReason()).contains("");
358    }
359
360    @Test
361    public void is_type_mockable_give_empty_reason_if_type_is_mockable() {
362        MockMaker.TypeMockability mockable = mockMaker.isTypeMockable(SomeClass.class);
363        assertThat(mockable.mockable()).isTrue();
364        assertThat(mockable.nonMockableReason()).isEqualTo("");
365    }
366
367    @Test
368    public void is_type_mockable_give_allow_final_mockable_from_JDK() {
369        MockMaker.TypeMockability mockable = mockMaker.isTypeMockable(Pattern.class);
370        assertThat(mockable.mockable()).isTrue();
371        assertThat(mockable.nonMockableReason()).isEqualTo("");
372    }
373
374    @Test
375    public void test_parameters_retention() throws Exception {
376        assumeTrue(ClassFileVersion.ofThisVm().isAtLeast(JAVA_V8));
377
378        Class<?> typeWithParameters =
379                new ByteBuddy()
380                        .subclass(Object.class)
381                        .defineMethod("foo", void.class, Visibility.PUBLIC)
382                        .withParameter(String.class, "bar")
383                        .intercept(StubMethod.INSTANCE)
384                        .make()
385                        .load(null)
386                        .getLoaded();
387
388        MockCreationSettings<?> settings = settingsFor(typeWithParameters);
389        @SuppressWarnings("unchecked")
390        Object proxy = mockMaker.createMock(settings, new MockHandlerImpl(settings));
391
392        assertThat(proxy.getClass()).isEqualTo(typeWithParameters);
393        assertThat(
394                        new TypeDescription.ForLoadedType(typeWithParameters)
395                                .getDeclaredMethods()
396                                .filter(named("foo"))
397                                .getOnly()
398                                .getParameters()
399                                .getOnly()
400                                .getName())
401                .isEqualTo("bar");
402    }
403
404    @Test
405    public void test_constant_dynamic_compatibility() throws Exception {
406        assumeTrue(ClassFileVersion.ofThisVm().isAtLeast(JAVA_V11));
407
408        Class<?> typeWithCondy =
409                new ByteBuddy()
410                        .subclass(Callable.class)
411                        .method(named("call"))
412                        .intercept(FixedValue.value(JavaConstant.Dynamic.ofNullConstant()))
413                        .make()
414                        .load(null)
415                        .getLoaded();
416
417        MockCreationSettings<?> settings = settingsFor(typeWithCondy);
418        @SuppressWarnings("unchecked")
419        Object proxy = mockMaker.createMock(settings, new MockHandlerImpl(settings));
420
421        assertThat(proxy.getClass()).isEqualTo(typeWithCondy);
422    }
423
424    @Test
425    public void test_clear_mock_clears_handler() {
426        MockCreationSettings<GenericSubClass> settings = settingsFor(GenericSubClass.class);
427        GenericSubClass proxy =
428                mockMaker.createMock(settings, new MockHandlerImpl<GenericSubClass>(settings));
429        assertThat(mockMaker.getHandler(proxy)).isNotNull();
430
431        // when
432        mockMaker.clearMock(proxy);
433
434        // then
435        assertThat(mockMaker.getHandler(proxy)).isNull();
436    }
437
438    @Test
439    public void test_clear_all_mock_clears_handler() {
440        MockCreationSettings<GenericSubClass> settings = settingsFor(GenericSubClass.class);
441        GenericSubClass proxy1 =
442                mockMaker.createMock(settings, new MockHandlerImpl<GenericSubClass>(settings));
443        assertThat(mockMaker.getHandler(proxy1)).isNotNull();
444
445        settings = settingsFor(GenericSubClass.class);
446        GenericSubClass proxy2 =
447                mockMaker.createMock(settings, new MockHandlerImpl<GenericSubClass>(settings));
448        assertThat(mockMaker.getHandler(proxy1)).isNotNull();
449
450        // when
451        mockMaker.clearAllMocks();
452
453        // then
454        assertThat(mockMaker.getHandler(proxy1)).isNull();
455        assertThat(mockMaker.getHandler(proxy2)).isNull();
456    }
457
458    protected static <T> MockCreationSettings<T> settingsFor(
459            Class<T> type, Class<?>... extraInterfaces) {
460        MockSettingsImpl<T> mockSettings = new MockSettingsImpl<T>();
461        mockSettings.setTypeToMock(type);
462        mockSettings.defaultAnswer(new Returns("bar"));
463        if (extraInterfaces.length > 0) mockSettings.extraInterfaces(extraInterfaces);
464        return mockSettings;
465    }
466
467    @Test
468    public void testMockDispatcherIsRelocated() throws Exception {
469        assertThat(
470                        InlineByteBuddyMockMaker.class
471                                .getClassLoader()
472                                .getResource(
473                                        "org/mockito/internal/creation/bytebuddy/inject/MockMethodDispatcher.raw"))
474                .isNotNull();
475    }
476
477    private static final class FinalClass {
478
479        public String foo() {
480            return "foo";
481        }
482    }
483
484    private static final class FinalSpy {
485
486        private final String aString;
487        private final boolean aBoolean;
488        private final byte aByte;
489        private final short aShort;
490        private final char aChar;
491        private final int anInt;
492        private final long aLong;
493        private final float aFloat;
494        private final double aDouble;
495
496        private FinalSpy(
497                String aString,
498                boolean aBoolean,
499                byte aByte,
500                short aShort,
501                char aChar,
502                int anInt,
503                long aLong,
504                float aFloat,
505                double aDouble) {
506            this.aString = aString;
507            this.aBoolean = aBoolean;
508            this.aByte = aByte;
509            this.aShort = aShort;
510            this.aChar = aChar;
511            this.anInt = anInt;
512            this.aLong = aLong;
513            this.aFloat = aFloat;
514            this.aDouble = aDouble;
515        }
516    }
517
518    private static class NonConstructableClass {
519
520        private NonConstructableClass() {
521            throw new AssertionError();
522        }
523
524        public String foo() {
525            return "foo";
526        }
527    }
528
529    private enum EnumClass {
530        INSTANCE;
531
532        public String foo() {
533            return "foo";
534        }
535    }
536
537    private abstract static class FinalMethodAbstractType {
538
539        public final String foo() {
540            return "foo";
541        }
542
543        public abstract String bar();
544    }
545
546    private static class FinalMethod {
547
548        public final String foo() {
549            return "foo";
550        }
551    }
552
553    private interface SampleInterface {
554
555        String bar();
556    }
557
558    /*package-private*/ abstract class PackagePrivateSuperClass {
559
560        public abstract String indirect();
561
562        public String value() {
563            return indirect() + "qux";
564        }
565    }
566
567    public class NonPackagePrivateSubClass extends PackagePrivateSuperClass {
568
569        @Override
570        public String indirect() {
571            return "foo";
572        }
573    }
574
575    public static class GenericClass<T> {
576
577        public T value() {
578            return null;
579        }
580    }
581
582    public static class GenericSubClass extends GenericClass<String> {}
583
584    public static class ExceptionThrowingClass {
585        public IOException getException() {
586            try {
587                throwException();
588            } catch (IOException ex) {
589                return ex;
590            }
591            return null;
592        }
593
594        public void throwException() throws IOException {
595            internalThrowException(1);
596        }
597
598        void internalThrowException(int test) throws IOException {
599            // some lines of code, so the exception is not thrown in the first line of the method
600            int i = 0;
601            if (test != i) {
602                throw new IOException("fatal");
603            }
604        }
605    }
606}
607
Full Screen

Accelerate Your Automation Test Cycles With LambdaTest

Leverage LambdaTest’s cloud-based platform to execute your automation tests in parallel and trim down your test execution time significantly. Your first 100 automation testing minutes are on us.

Try LambdaTest

Most used method in InlineDelegateByteBuddyMockMakerTest

Trigger code on LambdaTest Cloud Grid

Execute automation tests with on a cloud-based Grid of 3000+ real browsers and operating systems for both web and mobile applications.

Test now for Free
LambdaTestX

We use cookies to give you the best experience. Cookies help to provide a more personalized experience and relevant advertising for you, and web analytics for us. Learn More in our Cookies policy, Privacy & Terms of service

Allow Cookie
Sarah

I hope you find the best code examples for your project.

If you want to accelerate automated browser testing, try LambdaTest. Your first 100 automation testing minutes are FREE.

Sarah Elson (Product & Growth Lead)