Best Mockito code snippet using org.mockito.internal.util.reflection.FieldInitializer
Source:FieldInitializerTest.java
...5package org.mockito.internal.util.reflection;6import org.junit.Test;7import org.mockito.InjectMocks;8import org.mockito.exceptions.base.MockitoException;9import org.mockito.internal.util.reflection.FieldInitializer.ConstructorArgumentResolver;10import java.lang.reflect.Field;11import java.lang.reflect.InvocationTargetException;12import static org.junit.Assert.*;13import static org.mockito.BDDMockito.given;14import static org.mockito.Matchers.any;15import static org.mockito.Mockito.mock;16public class FieldInitializerTest {17 private StaticClass alreadyInstantiated = new StaticClass();18 private StaticClass noConstructor;19 private StaticClassWithDefaultConstructor defaultConstructor;20 private StaticClassWithPrivateDefaultConstructor privateDefaultConstructor;21 private StaticClassWithoutDefaultConstructor noDefaultConstructor;22 private StaticClassThrowingExceptionDefaultConstructor throwingExDefaultConstructor;23 private AbstractStaticClass abstractType;24 private Interface interfaceType;25 private InnerClassType innerClassType;26 private AbstractStaticClass instantiatedAbstractType = new ConcreteStaticClass();27 private Interface instantiatedInterfaceType = new ConcreteStaticClass();28 private InnerClassType instantiatedInnerClassType = new InnerClassType();29 @Test30 public void should_keep_same_instance_if_field_initialized() throws Exception {31 final StaticClass backupInstance = alreadyInstantiated;32 FieldInitializer fieldInitializer = new FieldInitializer(this, field("alreadyInstantiated"));33 FieldInitializationReport report = fieldInitializer.initialize();34 assertSame(backupInstance, report.fieldInstance());35 assertFalse(report.fieldWasInitialized());36 assertFalse(report.fieldWasInitializedUsingContructorArgs());37 }38 @Test39 public void should_instantiate_field_when_type_has_no_constructor() throws Exception {40 FieldInitializer fieldInitializer = new FieldInitializer(this, field("noConstructor"));41 FieldInitializationReport report = fieldInitializer.initialize();42 assertNotNull(report.fieldInstance());43 assertTrue(report.fieldWasInitialized());44 assertFalse(report.fieldWasInitializedUsingContructorArgs());45 }46 @Test47 public void should_instantiate_field_with_default_constructor() throws Exception {48 FieldInitializer fieldInitializer = new FieldInitializer(this, field("defaultConstructor"));49 FieldInitializationReport report = fieldInitializer.initialize();50 assertNotNull(report.fieldInstance());51 assertTrue(report.fieldWasInitialized());52 assertFalse(report.fieldWasInitializedUsingContructorArgs());53 }54 @Test55 public void should_instantiate_field_with_private_default_constructor() throws Exception {56 FieldInitializer fieldInitializer = new FieldInitializer(this, field("privateDefaultConstructor"));57 FieldInitializationReport report = fieldInitializer.initialize();58 assertNotNull(report.fieldInstance());59 assertTrue(report.fieldWasInitialized());60 assertFalse(report.fieldWasInitializedUsingContructorArgs());61 }62 @Test(expected = MockitoException.class)63 public void should_fail_to_instantiate_field_if_no_default_constructor() throws Exception {64 FieldInitializer fieldInitializer = new FieldInitializer(this, field("noDefaultConstructor"));65 fieldInitializer.initialize();66 }67 @Test68 public void should_fail_to_instantiate_field_if_default_constructor_throws_exception() throws Exception {69 FieldInitializer fieldInitializer = new FieldInitializer(this, field("throwingExDefaultConstructor"));70 try {71 fieldInitializer.initialize();72 fail();73 } catch (MockitoException e) {74 InvocationTargetException ite = (InvocationTargetException) e.getCause();75 assertTrue(ite.getTargetException() instanceof NullPointerException);76 assertEquals("business logic failed", ite.getTargetException().getMessage());77 }78 }79 @Test(expected = MockitoException.class)80 public void should_fail_for_abstract_field() throws Exception {81 new FieldInitializer(this, field("abstractType"));82 }83 @Test84 public void should_not_fail_if_abstract_field_is_instantiated() throws Exception {85 new FieldInitializer(this, field("instantiatedAbstractType"));86 }87 @Test(expected = MockitoException.class)88 public void should_fail_for_interface_field() throws Exception {89 new FieldInitializer(this, field("interfaceType"));90 }91 @Test92 public void should_not_fail_if_interface_field_is_instantiated() throws Exception {93 new FieldInitializer(this, field("instantiatedInterfaceType"));94 }95 @Test(expected = MockitoException.class)96 public void should_fail_for_local_type_field() throws Exception {97 // when98 class LocalType { }99 class TheTestWithLocalType {100 @InjectMocks LocalType field;101 }102 TheTestWithLocalType testWithLocalType = new TheTestWithLocalType();103 // when104 new FieldInitializer(testWithLocalType, testWithLocalType.getClass().getDeclaredField("field"));105 }106 @Test107 public void should_not_fail_if_local_type_field_is_instantiated() throws Exception {108 // when109 class LocalType { }110 class TheTestWithLocalType {111 @InjectMocks LocalType field = new LocalType();112 }113 TheTestWithLocalType testWithLocalType = new TheTestWithLocalType();114 // when115 new FieldInitializer(testWithLocalType, testWithLocalType.getClass().getDeclaredField("field"));116 }117 @Test(expected = MockitoException.class)118 public void should_fail_for_inner_class_field() throws Exception {119 new FieldInitializer(this, field("innerClassType"));120 }121 @Test122 public void should_not_fail_if_inner_class_field_is_instantiated() throws Exception {123 new FieldInitializer(this, field("instantiatedInnerClassType"));124 }125 @Test126 public void can_instantiate_class_with_parameterized_constructor() throws Exception {127 ConstructorArgumentResolver resolver = given(mock(ConstructorArgumentResolver.class).resolveTypeInstances(any(Class.class)))128 .willReturn(new Object[]{null}).getMock();129 new FieldInitializer(this, field("noDefaultConstructor"), resolver).initialize();130 assertNotNull(noDefaultConstructor);131 }132 private Field field(String fieldName) throws NoSuchFieldException {133 return this.getClass().getDeclaredField(fieldName);134 }135 static class StaticClass {136 }137 static class StaticClassWithDefaultConstructor {138 StaticClassWithDefaultConstructor() { }139 }140 static class StaticClassWithPrivateDefaultConstructor {141 private StaticClassWithPrivateDefaultConstructor() { }142 }143 static class StaticClassWithoutDefaultConstructor {...
Source:GwtSpyAnnotationEngine.java
...4import org.mockito.exceptions.base.MockitoException;5import org.mockito.internal.configuration.SpyAnnotationEngine;6import org.mockito.internal.util.MockUtil;7import org.mockito.internal.util.reflection.FieldInitializationReport;8import org.mockito.internal.util.reflection.FieldInitializer;9import java.lang.annotation.Annotation;10import java.lang.reflect.Field;11import static org.mockito.Mockito.withSettings;12/**13 * Overrides Mockito's SpyAnnotationEngine to handle {@link com.googlecode.gwt.test.Mock}14 * annotation.15 *16 * @author Gael Lazzari17 */18class GwtSpyAnnotationEngine extends SpyAnnotationEngine {19 @Override20 @SuppressWarnings("deprecation")21 // for MockitoAnnotations.Mock22 public void process(Class<?> context, Object testInstance) {23 Field[] fields = context.getDeclaredFields();24 for (Field field : fields) {25 if (field.isAnnotationPresent(Spy.class) && !field.isAnnotationPresent(InjectMocks.class)) {26 assertNoIncompatibleAnnotations(Spy.class, field, com.googlecode.gwt.test.Mock.class,27 Mock.class, org.mockito.MockitoAnnotations.Mock.class, Captor.class);28 Object instance = null;29 try {30 FieldInitializationReport report = new FieldInitializer(testInstance, field).initialize();31 instance = report.fieldInstance();32 } catch (MockitoException e) {33 new Reporter().cannotInitializeForSpyAnnotation(field.getName(), e);34 }35 try {36 if (new MockUtil().isMock(instance)) {37 // instance has been spied earlier38 // for example happens when MockitoAnnotations.initMocks is called two times.39 Mockito.reset(instance);40 } else {41 field.setAccessible(true);42 field.set(testInstance, Mockito.mock(43 instance.getClass(),44 withSettings().spiedInstance(instance).defaultAnswer(...
Source:ConstructorInjection.java
...4 */5package org.mockito.internal.configuration.injection;6import org.mockito.exceptions.base.MockitoException;7import org.mockito.internal.util.reflection.FieldInitializationReport;8import org.mockito.internal.util.reflection.FieldInitializer;9import org.mockito.internal.util.reflection.FieldInitializer.ConstructorArgumentResolver;10import static org.mockito.internal.exceptions.Reporter.fieldInitialisationThrewException;11import java.lang.reflect.Field;12import java.lang.reflect.InvocationTargetException;13import java.util.ArrayList;14import java.util.List;15import java.util.Set;16/**17 * Injection strategy based on constructor.18 *19 * <p>20 * The strategy will search for the constructor with most parameters21 * and try to resolve mocks by type.22 * </p>23 *24 * <blockquote>25 * TODO on missing mock type, shall it abandon or create "noname" mocks.26 * TODO and what if the arg type is not mockable.27 * </blockquote>28 *29 * <p>30 * For now the algorithm tries to create anonymous mocks if an argument type is missing.31 * If not possible the algorithm abandon resolution.32 * </p>33 */34public class ConstructorInjection extends MockInjectionStrategy {35 public ConstructorInjection() { }36 public boolean processInjection(Field field, Object fieldOwner, Set<Object> mockCandidates) {37 try {38 SimpleArgumentResolver simpleArgumentResolver = new SimpleArgumentResolver(mockCandidates);39 FieldInitializationReport report = new FieldInitializer(fieldOwner, field, simpleArgumentResolver).initialize();40 return report.fieldWasInitializedUsingContructorArgs();41 } catch (MockitoException e) {42 if(e.getCause() instanceof InvocationTargetException) {43 Throwable realCause = e.getCause().getCause();44 throw fieldInitialisationThrewException(field, realCause);45 }46 // other causes should be fine47 return false;48 }49 }50 /**51 * Returns mocks that match the argument type, if not possible assigns null.52 */53 static class SimpleArgumentResolver implements ConstructorArgumentResolver {...
FieldInitializer
Using AI Code Generation
1import org.mockito.internal.util.reflection.FieldInitializer;2import org.mockito.internal.util.reflection.FieldReader;3public class Main {4 public static void main(String[] args) {5 FieldInitializer fieldInitializer = new FieldInitializer();6 FieldReader fieldReader = new FieldReader();7 TestClass testClass = new TestClass();8 fieldInitializer.initializeFields(testClass);9 System.out.println("name: "+fieldReader.readField("name", testClass));10 System.out.println("age: "+fieldReader.readField("age", testClass));11 System.out.println("address: "+fieldReader.readField("address", testClass));12 }13}14import org.mockito.internal.util.reflection.FieldInitializer;15import org.mockito.internal.util.reflection.FieldReader;16public class Main {17 public static void main(String[] args) {18 FieldInitializer fieldInitializer = new FieldInitializer();19 FieldReader fieldReader = new FieldReader();20 TestClass testClass = new TestClass();21 fieldInitializer.initializeFields(testClass);22 System.out.println("name: "+fieldReader.readField("name", testClass));23 System.out.println("age: "+fieldReader.readField("age", testClass));24 System.out.println("address: "+fieldReader.readField("address", testClass));25 }26}27import org.mockito.internal.util.reflection.FieldInitializer;28import org.mockito.internal.util.reflection.FieldReader;29public class Main {30 public static void main(String[] args) {31 FieldInitializer fieldInitializer = new FieldInitializer();32 FieldReader fieldReader = new FieldReader();33 TestClass testClass = new TestClass();34 fieldInitializer.initializeFields(testClass);35 System.out.println("name: "+fieldReader.readField("name", testClass));36 System.out.println("age: "+fieldReader.readField("age", testClass));37 System.out.println("address: "+fieldReader.readField("address", testClass));38 }39}40import org.mockito.internal.util.reflection.FieldInitializer;41import org.mockito.internal.util.reflection.FieldReader;42public class Main {43 public static void main(String[] args) {
FieldInitializer
Using AI Code Generation
1package com.mycompany.app;2import org.mockito.internal.util.reflection.FieldInitializer;3{4 public static void main( String[] args )5 {6 FieldInitializer fieldInitializer = new FieldInitializer();7 fieldInitializer.initializeFields(new Object());8 }9}10package com.mycompany.app;11import org.mockito.internal.util.reflection.FieldInitializer;12{13 public static void main( String[] args )14 {15 FieldInitializer fieldInitializer = new FieldInitializer();16 fieldInitializer.initializeFields(new Object());17 }18}19Exception in thread "main" java.lang.RuntimeException: java.lang.NoSuchMethodError: org.mockito.internal.util.reflection.FieldInitializer.initializeFields(Ljava/lang/Object;)V20 at org.mockito.internal.util.reflection.FieldInitializer.initializeFields(FieldInitializer.java:17)21 at com.mycompany.app.App.main(App.java:10)22Caused by: java.lang.NoSuchMethodError: org.mockito.internal.util.reflection.FieldInitializer.initializeFields(Ljava/lang/Object;)V23 at com.mycompany.app.App.main(App.java:10)
FieldInitializer
Using AI Code Generation
1import org.mockito.internal.util.reflection.FieldInitializer;2import org.mockito.internal.util.reflection.FieldInitializationReport;3public class FieldInitializerTest {4 public static void main(String[] args) {5 FieldInitializerTest test = new FieldInitializerTest();6 test.testInitializeFields();7 }8 public void testInitializeFields() {9 FieldInitializer initializer = new FieldInitializer();10 FieldInitializationReport report = initializer.initializeFields(this);11 System.out.println(report);12 }13 private int i = 0;14 public int getI() {
FieldInitializer
Using AI Code Generation
1package com.test;2import org.mockito.internal.util.reflection.FieldInitializer;3import org.mockito.internal.util.reflection.FieldReader;4public class Test {5public static void main(String[] args) {6FieldInitializer fieldInitializer = new FieldInitializer();7fieldInitializer.initializeFields(new Test(), new FieldReader() {8public Object read(Object target, String name) {9if ("name".equals(name)) {10return "Test";11}12return null;13}14});15System.out.println(name);16}17}
FieldInitializer
Using AI Code Generation
1package org.mockito.internal.util.reflection;2import org.mockito.internal.util.reflection.FieldInitializer;3import java.lang.reflect.Field;4import java.lang.reflect.Modifier;5public class FieldInitializer {6 private static final Field[] NO_FIELDS = new Field[0];7 private final Object target;8 private final Field field;9 private final Object value;10 public FieldInitializer(Object target, Field field, Object value) {11 this.target = target;12 this.field = field;13 this.value = value;14 }15 public static FieldInitializer of(Object target, Field field, Object value) {16 return new FieldInitializer(target, field, value);17 }18 public static FieldInitializer of(Object target, String fieldName, Object value) {19 Field field = findField(target.getClass(), fieldName);20 if (field == null) {21 throw new RuntimeException("Cannot find field '" + fieldName + "' on " + target);22 }23 return of(target, field, value);24 }25 public static Field findField(Class<?> clazz, String fieldName) {26 for (Field field : clazz.getDeclaredFields()) {27 if (field.getName().equals(fieldName)) {28 return field;29 }30 }31 return null;32 }33 public static Field[] findFields(Class<?> clazz) {34 return clazz.getDeclaredFields();35 }36 public static FieldInitializer of(Object target, String fieldName) {37 return of(target, fieldName, null);38 }39 public FieldInitializer initialize() {40 if (field == null) {41 return this;42 }43 try {44 field.setAccessible(true);45 field.set(target, value);46 } catch (Exception e) {47 throw new RuntimeException("Cannot set field value on " + field, e);48 }49 return this;50 }51 public FieldInitializer initializeAll() {52 for (Field field : findFields(target.getClass())) {53 of(target, field, value).initialize();54 }55 return this;56 }57 public FieldInitializer initializeAllExcept(String... fieldNames) {58 for (Field field : findFields(target.getClass())) {59 if (!isIn(field.getName(), fieldNames)) {60 of(target, field, value).initialize();61 }62 }63 return this;64 }65 public FieldInitializer initializeAllExcept(Field... fields) {66 for (Field field : findFields(target.getClass())) {67 if (!isIn(field, fields)) {68 of(target, field, value).initialize();
FieldInitializer
Using AI Code Generation
1import org.mockito.internal.util.reflection.FieldInitializer;2class Test {3 public static void main(String[] args) {4 FieldInitializer fieldInitializer = new FieldInitializer();5 fieldInitializer.initializeFields(new Test(), new Test());6 }7}8import org.mockito.internal.util.reflection.FieldInitializer;9class Test {10 private int a;11 public static void main(String[] args) {12 Test test1 = new Test();13 Test test2 = new Test();14 test1.a = 10;15 FieldInitializer fieldInitializer = new FieldInitializer();16 fieldInitializer.initializeFields(test1, test2);17 System.out.println(test1.a);18 }19}
FieldInitializer
Using AI Code Generation
1package org.mockito.internal.util.reflection;2import java.lang.reflect.Field;3public class FieldInitializer {4 public static void setField(Object obj, Field field, Object value) {5 boolean wasAccessible = field.isAccessible();6 try {7 field.setAccessible(true);8 field.set(obj, value);9 } catch (IllegalAccessException e) {10 throw new RuntimeException(e);11 } finally {12 field.setAccessible(wasAccessible);13 }14 }15}16package org.mockito.internal.util.reflection;17import java.lang.reflect.Field;18public class FieldInitializer {19 public static void setField(Object obj, Field field, Object value) {20 boolean wasAccessible = field.isAccessible();21 try {22 field.setAccessible(true);23 field.set(obj, value);24 } catch (IllegalAccessException e) {25 throw new RuntimeException(e);26 } finally {27 field.setAccessible(wasAccessible);28 }29 }30}31package org.mockito.internal.util.reflection;32import java.lang.reflect.Field;33public class FieldInitializer {34 public static void setField(Object obj, Field field, Object value) {35 boolean wasAccessible = field.isAccessible();36 try {37 field.setAccessible(true);38 field.set(obj, value);39 } catch (IllegalAccessException e) {40 throw new RuntimeException(e);41 } finally {42 field.setAccessible(wasAccessible);43 }44 }45}46package org.mockito.internal.util.reflection;47import java.lang.reflect.Field;48public class FieldInitializer {49 public static void setField(Object obj, Field field, Object value) {50 boolean wasAccessible = field.isAccessible();51 try {52 field.setAccessible(true);53 field.set(obj, value);54 } catch (IllegalAccessException e) {55 throw new RuntimeException(e);56 } finally {57 field.setAccessible(wasAccessible);58 }59 }60}
FieldInitializer
Using AI Code Generation
1package com.mycompany.myapp;2import org.mockito.internal.util.reflection.FieldInitializer;3public class MyClass1 {4 private String str;5 public MyClass1() {6 FieldInitializer.initialize(this);7 }8 public String getStr() {9 return str;10 }11}12package com.mycompany.myapp;13import org.mockito.internal.util.reflection.FieldInitializer;14public class MyClass2 {15 private String str;16 public MyClass2() {17 FieldInitializer.initialize(this);18 }19 public String getStr() {20 return str;21 }22}23package com.mycompany.myapp;24import org.mockito.internal.util.reflection.FieldInitializer;25public class MyClass3 {26 private String str;27 public MyClass3() {28 FieldInitializer.initialize(this);29 }30 public String getStr() {31 return str;32 }33}34package com.mycompany.myapp;35import org.mockito.internal.util.reflection.FieldInitializer;36public class MyClass4 {37 private String str;38 public MyClass4() {39 FieldInitializer.initialize(this);40 }41 public String getStr() {42 return str;43 }44}45package com.mycompany.myapp;46import org.mockito.internal.util.reflection.FieldInitializer;47public class MyClass5 {48 private String str;49 public MyClass5() {50 FieldInitializer.initialize(this);51 }52 public String getStr() {53 return str;54 }55}56package com.mycompany.myapp;57import org.mockito.internal.util.reflection.FieldInitializer;58public class MyClass6 {59 private String str;60 public MyClass6() {61 FieldInitializer.initialize(this);62 }63 public String getStr() {64 return str;65 }66}
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!!