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

1

7

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());
}
Davis answered 9/3, 2022 at 6:3 Comment(2)
Is this the whole testcase? Furthermore it would be helpful to see the test which should be tested..Orphaorphan
@Orphaorphan I have updated the code. I am not sure what can I use to replace FieldSetter.setField ?Davis
L
9

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);
    }
}

}
Lodging answered 9/6, 2022 at 9:10 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.