Best Mockito code snippet using org.mockito.internal.creation.bytebuddy.InlineDelegateByteBuddyMockMakerTest.NonConstructableClass
Source:InlineDelegateByteBuddyMockMakerTest.java
...77 });78 }79 @Test80 public void should_create_mock_from_non_constructable_class() throws Exception {81 MockCreationSettings<NonConstructableClass> settings =82 settingsFor(NonConstructableClass.class);83 NonConstructableClass proxy =84 mockMaker.createMock(85 settings, new MockHandlerImpl<NonConstructableClass>(settings));86 assertThat(proxy.foo()).isEqualTo("bar");87 }88 @Test89 public void should_create_mock_from_final_class_in_the_JDK() throws Exception {90 MockCreationSettings<Pattern> settings = settingsFor(Pattern.class);91 Pattern proxy = mockMaker.createMock(settings, new MockHandlerImpl<Pattern>(settings));92 assertThat(proxy.pattern()).isEqualTo("bar");93 }94 @Test95 public void should_create_mock_from_abstract_class_with_final_method() throws Exception {96 MockCreationSettings<FinalMethodAbstractType> settings =97 settingsFor(FinalMethodAbstractType.class);98 FinalMethodAbstractType proxy =99 mockMaker.createMock(100 settings, new MockHandlerImpl<FinalMethodAbstractType>(settings));101 assertThat(proxy.foo()).isEqualTo("bar");102 assertThat(proxy.bar()).isEqualTo("bar");103 }104 @Test105 public void should_create_mock_from_final_class_with_interface_methods() throws Exception {106 MockCreationSettings<FinalMethod> settings =107 settingsFor(FinalMethod.class, SampleInterface.class);108 FinalMethod proxy =109 mockMaker.createMock(settings, new MockHandlerImpl<FinalMethod>(settings));110 assertThat(proxy.foo()).isEqualTo("bar");111 assertThat(((SampleInterface) proxy).bar()).isEqualTo("bar");112 }113 @Test114 public void should_detect_non_overridden_generic_method_of_supertype() throws Exception {115 MockCreationSettings<GenericSubClass> settings = settingsFor(GenericSubClass.class);116 GenericSubClass proxy =117 mockMaker.createMock(settings, new MockHandlerImpl<GenericSubClass>(settings));118 assertThat(proxy.value()).isEqualTo("bar");119 }120 @Test121 public void should_create_mock_from_hashmap() throws Exception {122 MockCreationSettings<HashMap> settings = settingsFor(HashMap.class);123 HashMap proxy = mockMaker.createMock(settings, new MockHandlerImpl<HashMap>(settings));124 assertThat(proxy.get(null)).isEqualTo("bar");125 }126 @Test127 @SuppressWarnings("unchecked")128 public void should_throw_exception_redefining_unmodifiable_class() {129 MockCreationSettings settings = settingsFor(int.class);130 try {131 mockMaker.createMock(settings, new MockHandlerImpl(settings));132 fail("Expected a MockitoException");133 } catch (MockitoException e) {134 e.printStackTrace();135 assertThat(e).hasMessageContaining("Could not modify all classes");136 }137 }138 @Test139 @SuppressWarnings("unchecked")140 public void should_throw_exception_redefining_array() {141 int[] array = new int[5];142 MockCreationSettings<? extends int[]> settings = settingsFor(array.getClass());143 try {144 mockMaker.createMock(settings, new MockHandlerImpl(settings));145 fail("Expected a MockitoException");146 } catch (MockitoException e) {147 assertThat(e).hasMessageContaining("Arrays cannot be mocked");148 }149 }150 @Test151 public void should_create_mock_from_enum() throws Exception {152 MockCreationSettings<EnumClass> settings = settingsFor(EnumClass.class);153 EnumClass proxy = mockMaker.createMock(settings, new MockHandlerImpl<EnumClass>(settings));154 assertThat(proxy.foo()).isEqualTo("bar");155 }156 @Test157 public void should_fail_at_creating_a_mock_of_a_final_class_with_explicit_serialization()158 throws Exception {159 MockCreationSettings<FinalClass> settings =160 new CreationSettings<FinalClass>()161 .setTypeToMock(FinalClass.class)162 .setSerializableMode(SerializableMode.BASIC);163 try {164 mockMaker.createMock(settings, new MockHandlerImpl<FinalClass>(settings));165 fail("Expected a MockitoException");166 } catch (MockitoException e) {167 assertThat(e)168 .hasMessageContaining("Unsupported settings")169 .hasMessageContaining("serialization")170 .hasMessageContaining("extra interfaces");171 }172 }173 @Test174 public void should_fail_at_creating_a_mock_of_a_final_class_with_extra_interfaces()175 throws Exception {176 MockCreationSettings<FinalClass> settings =177 new CreationSettings<FinalClass>()178 .setTypeToMock(FinalClass.class)179 .setExtraInterfaces(Sets.<Class<?>>newSet(List.class));180 try {181 mockMaker.createMock(settings, new MockHandlerImpl<FinalClass>(settings));182 fail("Expected a MockitoException");183 } catch (MockitoException e) {184 assertThat(e)185 .hasMessageContaining("Unsupported settings")186 .hasMessageContaining("serialization")187 .hasMessageContaining("extra interfaces");188 }189 }190 @Test191 public void should_mock_interface() {192 MockSettingsImpl<Set> mockSettings = new MockSettingsImpl<Set>();193 mockSettings.setTypeToMock(Set.class);194 mockSettings.defaultAnswer(new Returns(10));195 Set<?> proxy = mockMaker.createMock(mockSettings, new MockHandlerImpl<Set>(mockSettings));196 assertThat(proxy.size()).isEqualTo(10);197 }198 @Test199 public void should_mock_interface_to_string() {200 MockSettingsImpl<Set> mockSettings = new MockSettingsImpl<Set>();201 mockSettings.setTypeToMock(Set.class);202 mockSettings.defaultAnswer(new Returns("foo"));203 Set<?> proxy = mockMaker.createMock(mockSettings, new MockHandlerImpl<Set>(mockSettings));204 assertThat(proxy.toString()).isEqualTo("foo");205 }206 /**207 * @see <a href="https://github.com/mockito/mockito/issues/2154">https://github.com/mockito/mockito/issues/2154</a>208 */209 @Test210 public void should_mock_class_to_string() {211 MockSettingsImpl<Object> mockSettings = new MockSettingsImpl<Object>();212 mockSettings.setTypeToMock(Object.class);213 mockSettings.defaultAnswer(new Returns("foo"));214 Object proxy =215 mockMaker.createMock(mockSettings, new MockHandlerImpl<Object>(mockSettings));216 assertThat(proxy.toString()).isEqualTo("foo");217 }218 @Test219 public void should_leave_causing_stack() throws Exception {220 MockSettingsImpl<ExceptionThrowingClass> settings = new MockSettingsImpl<>();221 settings.setTypeToMock(ExceptionThrowingClass.class);222 settings.defaultAnswer(Answers.CALLS_REAL_METHODS);223 Optional<ExceptionThrowingClass> proxy =224 mockMaker.createSpy(225 settings, new MockHandlerImpl<>(settings), new ExceptionThrowingClass());226 StackTraceElement[] returnedStack = null;227 try {228 proxy.get().throwException();229 } catch (IOException ex) {230 returnedStack = ex.getStackTrace();231 }232 assertNotNull("Stack trace from mockito expected", returnedStack);233 assertEquals(ExceptionThrowingClass.class.getName(), returnedStack[0].getClassName());234 assertEquals("internalThrowException", returnedStack[0].getMethodName());235 }236 @Test237 public void should_remove_recursive_self_call_from_stack_trace() throws Exception {238 StackTraceElement[] stack =239 new StackTraceElement[] {240 new StackTraceElement("foo", "", "", -1),241 new StackTraceElement(SampleInterface.class.getName(), "", "", -1),242 new StackTraceElement("qux", "", "", -1),243 new StackTraceElement("bar", "", "", -1),244 new StackTraceElement("baz", "", "", -1)245 };246 Throwable throwable = new Throwable();247 throwable.setStackTrace(stack);248 throwable = MockMethodAdvice.hideRecursiveCall(throwable, 2, SampleInterface.class);249 assertThat(throwable.getStackTrace())250 .isEqualTo(251 new StackTraceElement[] {252 new StackTraceElement("foo", "", "", -1),253 new StackTraceElement("bar", "", "", -1),254 new StackTraceElement("baz", "", "", -1)255 });256 }257 @Test258 public void should_handle_missing_or_inconsistent_stack_trace() throws Exception {259 Throwable throwable = new Throwable();260 throwable.setStackTrace(new StackTraceElement[0]);261 assertThat(MockMethodAdvice.hideRecursiveCall(throwable, 0, SampleInterface.class))262 .isSameAs(throwable);263 }264 @Test265 public void should_provide_reason_for_wrapper_class() {266 MockMaker.TypeMockability mockable = mockMaker.isTypeMockable(Integer.class);267 assertThat(mockable.nonMockableReason())268 .isEqualTo("Cannot mock wrapper types, String.class or Class.class");269 }270 @Test271 public void should_provide_reason_for_vm_unsupported() {272 MockMaker.TypeMockability mockable = mockMaker.isTypeMockable(int[].class);273 assertThat(mockable.nonMockableReason())274 .isEqualTo("VM does not support modification of given type");275 }276 @Test277 public void should_mock_method_of_package_private_class() throws Exception {278 MockCreationSettings<NonPackagePrivateSubClass> settings =279 settingsFor(NonPackagePrivateSubClass.class);280 NonPackagePrivateSubClass proxy =281 mockMaker.createMock(282 settings, new MockHandlerImpl<NonPackagePrivateSubClass>(settings));283 assertThat(proxy.value()).isEqualTo("bar");284 }285 @Test286 public void is_type_mockable_excludes_String() {287 MockMaker.TypeMockability mockable = mockMaker.isTypeMockable(String.class);288 assertThat(mockable.mockable()).isFalse();289 assertThat(mockable.nonMockableReason())290 .contains("Cannot mock wrapper types, String.class or Class.class");291 }292 @Test293 public void is_type_mockable_excludes_Class() {294 MockMaker.TypeMockability mockable = mockMaker.isTypeMockable(Class.class);295 assertThat(mockable.mockable()).isFalse();296 assertThat(mockable.nonMockableReason())297 .contains("Cannot mock wrapper types, String.class or Class.class");298 }299 @Test300 public void is_type_mockable_excludes_primitive_classes() {301 MockMaker.TypeMockability mockable = mockMaker.isTypeMockable(int.class);302 assertThat(mockable.mockable()).isFalse();303 assertThat(mockable.nonMockableReason()).contains("primitive");304 }305 @Test306 public void is_type_mockable_allows_anonymous() {307 Observer anonymous =308 new Observer() {309 @Override310 public void update(Observable o, Object arg) {}311 };312 MockMaker.TypeMockability mockable = mockMaker.isTypeMockable(anonymous.getClass());313 assertThat(mockable.mockable()).isTrue();314 assertThat(mockable.nonMockableReason()).contains("");315 }316 @Test317 public void is_type_mockable_give_empty_reason_if_type_is_mockable() {318 MockMaker.TypeMockability mockable = mockMaker.isTypeMockable(SomeClass.class);319 assertThat(mockable.mockable()).isTrue();320 assertThat(mockable.nonMockableReason()).isEqualTo("");321 }322 @Test323 public void is_type_mockable_give_allow_final_mockable_from_JDK() {324 MockMaker.TypeMockability mockable = mockMaker.isTypeMockable(Pattern.class);325 assertThat(mockable.mockable()).isTrue();326 assertThat(mockable.nonMockableReason()).isEqualTo("");327 }328 @Test329 public void test_parameters_retention() throws Exception {330 assumeTrue(ClassFileVersion.ofThisVm().isAtLeast(JAVA_V8));331 Class<?> typeWithParameters =332 new ByteBuddy()333 .subclass(Object.class)334 .defineMethod("foo", void.class, Visibility.PUBLIC)335 .withParameter(String.class, "bar")336 .intercept(StubMethod.INSTANCE)337 .make()338 .load(null)339 .getLoaded();340 MockCreationSettings<?> settings = settingsFor(typeWithParameters);341 @SuppressWarnings("unchecked")342 Object proxy = mockMaker.createMock(settings, new MockHandlerImpl(settings));343 assertThat(proxy.getClass()).isEqualTo(typeWithParameters);344 assertThat(345 new TypeDescription.ForLoadedType(typeWithParameters)346 .getDeclaredMethods()347 .filter(named("foo"))348 .getOnly()349 .getParameters()350 .getOnly()351 .getName())352 .isEqualTo("bar");353 }354 @Test355 public void test_constant_dynamic_compatibility() throws Exception {356 assumeTrue(ClassFileVersion.ofThisVm().isAtLeast(JAVA_V11));357 Class<?> typeWithCondy =358 new ByteBuddy()359 .subclass(Callable.class)360 .method(named("call"))361 .intercept(FixedValue.value(JavaConstant.Dynamic.ofNullConstant()))362 .make()363 .load(null)364 .getLoaded();365 MockCreationSettings<?> settings = settingsFor(typeWithCondy);366 @SuppressWarnings("unchecked")367 Object proxy = mockMaker.createMock(settings, new MockHandlerImpl(settings));368 assertThat(proxy.getClass()).isEqualTo(typeWithCondy);369 }370 @Test371 public void test_clear_mock_clears_handler() {372 MockCreationSettings<GenericSubClass> settings = settingsFor(GenericSubClass.class);373 GenericSubClass proxy =374 mockMaker.createMock(settings, new MockHandlerImpl<GenericSubClass>(settings));375 assertThat(mockMaker.getHandler(proxy)).isNotNull();376 // when377 mockMaker.clearMock(proxy);378 // then379 assertThat(mockMaker.getHandler(proxy)).isNull();380 }381 @Test382 public void test_clear_all_mock_clears_handler() {383 MockCreationSettings<GenericSubClass> settings = settingsFor(GenericSubClass.class);384 GenericSubClass proxy1 =385 mockMaker.createMock(settings, new MockHandlerImpl<GenericSubClass>(settings));386 assertThat(mockMaker.getHandler(proxy1)).isNotNull();387 settings = settingsFor(GenericSubClass.class);388 GenericSubClass proxy2 =389 mockMaker.createMock(settings, new MockHandlerImpl<GenericSubClass>(settings));390 assertThat(mockMaker.getHandler(proxy1)).isNotNull();391 // when392 mockMaker.clearAllMocks();393 // then394 assertThat(mockMaker.getHandler(proxy1)).isNull();395 assertThat(mockMaker.getHandler(proxy2)).isNull();396 }397 private static <T> MockCreationSettings<T> settingsFor(398 Class<T> type, Class<?>... extraInterfaces) {399 MockSettingsImpl<T> mockSettings = new MockSettingsImpl<T>();400 mockSettings.setTypeToMock(type);401 mockSettings.defaultAnswer(new Returns("bar"));402 if (extraInterfaces.length > 0) mockSettings.extraInterfaces(extraInterfaces);403 return mockSettings;404 }405 @Test406 public void testMockDispatcherIsRelocated() throws Exception {407 assertThat(408 InlineByteBuddyMockMaker.class409 .getClassLoader()410 .getResource(411 "org/mockito/internal/creation/bytebuddy/inject/MockMethodDispatcher.raw"))412 .isNotNull();413 }414 private static final class FinalClass {415 public String foo() {416 return "foo";417 }418 }419 private static final class FinalSpy {420 private final String aString;421 private final boolean aBoolean;422 private final byte aByte;423 private final short aShort;424 private final char aChar;425 private final int anInt;426 private final long aLong;427 private final float aFloat;428 private final double aDouble;429 private FinalSpy(430 String aString,431 boolean aBoolean,432 byte aByte,433 short aShort,434 char aChar,435 int anInt,436 long aLong,437 float aFloat,438 double aDouble) {439 this.aString = aString;440 this.aBoolean = aBoolean;441 this.aByte = aByte;442 this.aShort = aShort;443 this.aChar = aChar;444 this.anInt = anInt;445 this.aLong = aLong;446 this.aFloat = aFloat;447 this.aDouble = aDouble;448 }449 }450 private static class NonConstructableClass {451 private NonConstructableClass() {452 throw new AssertionError();453 }454 public String foo() {455 return "foo";456 }457 }458 private enum EnumClass {459 INSTANCE;460 public String foo() {461 return "foo";462 }463 }464 private abstract static class FinalMethodAbstractType {465 public final String foo() {...
NonConstructableClass
Using AI Code Generation
1NonConstructableClass mock = mock(NonConstructableClass.class);2when(mock.someMethod()).thenReturn("hello world");3assertEquals("hello world", mock.someMethod());4NonConstructableClass mock = mock(NonConstructableClass.class);5when(mock.someMethod()).thenReturn("hello world");6assertEquals("hello world", mock.someMethod());7NonConstructableClass mock = mock(NonConstructableClass.class);8when(mock.someMethod()).thenReturn("hello world");9assertEquals("hello world", mock.someMethod());10NonConstructableClass mock = mock(NonConstructableClass.class);11when(mock.someMethod()).thenReturn("hello world");12assertEquals("hello world", mock.someMethod());13NonConstructableClass mock = mock(NonConstructableClass.class);14when(mock.someMethod()).thenReturn("hello world");15assertEquals("hello world", mock.someMethod());16NonConstructableClass mock = mock(NonConstructableClass.class);17when(mock.someMethod()).thenReturn("hello world");18assertEquals("hello world", mock.someMethod());19NonConstructableClass mock = mock(NonConstructableClass.class);20when(mock.someMethod()).thenReturn("hello world");21assertEquals("hello world", mock.someMethod());22NonConstructableClass mock = mock(NonConstructableClass.class);23when(mock.someMethod()).thenReturn("hello world");24assertEquals("hello world", mock.someMethod());25NonConstructableClass mock = mock(NonConstruct
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!!