org.mockito.internal.util.reflection.FieldSetter; deprecated in mockito-core 4.3.1

In the below code FieldSetter.SetField was used for the test case but now as I have up upgraded to mockito-core 4.3.1. This no longer works. Can you please suggest to me what can I replace it with?

This is throwing an error as it is deprecated in mockito 4.3.1

import org.mockito.internal.util.reflection.FieldSetter;

@Rule
public AemContext context = new AemContext();
private FareRulesRequestProcessor fareRulesRequestProcessor = new FareRulesRequestProcessorImpl();
private FareRulesPathInfo pathInfo;
@Mock
private SlingHttpServletRequest mockRequest;
private FareRulesDataService mockFareRulesDataService;
@Before
public void before() throws Exception { mockFareRulesDataService = new FareRulesDataServiceImpl(); mockFareRulesDataService = mock(FareRulesDataService.class); PrivateAccessor.setField(fareRulesRequestProcessor, "fareRulesDataService", mockFareRulesDataService);
}
@Test
public void testFareRulesDataForRequest() throws NoSuchFieldException { when(mockRequest.getPathInfo()).thenReturn(FARE_RULES_PAGE_URL); FieldSetter.setField(fareRulesRequestProcessor, fareRulesRequestProcessor.getClass().getDeclaredField("validFareRulesDataMap"), getFareRulesDataMap()); FareRulesData fareRulesData = fareRulesRequestProcessor.getFareRulesData(mockRequest); assertEquals(FROM, fareRulesData.getDestinationFrom()); assertEquals(TO, fareRulesData.getDestinationTo()); assertEquals(MARKET, fareRulesData.getMarket()); assertTrue(fareRulesData.isFareRulesByMarket());
}
2

1 Answer

This was an internal class of Mockito, you should not depend on it. I ended up using this simple util instead:

//import java.lang.reflect.Field;
public class ReflectUtils { private ReflectUtils() {} public static void setField(Object object, String fieldName, Object value) { try { var field = object.getClass().getDeclaredField(fieldName); field.setAccessible(true); field.set(object, value); } catch (NoSuchFieldException | IllegalAccessException e) { throw new RuntimeException("Failed to set " + fieldName + " of object", e); } }
public static void setField(Object object, Field fld, Object value) { try { fld.setAccessible(true); fld.set(object, value); } catch (IllegalAccessException e) { String fieldName = null == fld ? "n/a" : fld.getName(); throw new RuntimeException("Failed to set " + fieldName + " of object", e); }
}
}

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

You Might Also Like