org.mockito.internal.util.reflection.FieldSetter;在 mockito-core 4.3.1 中已弃用

在下面的代码中,FieldSetter.SetField 用于测试用例,但现在我已经升级到 mockito-core 4.3.1。这不再有效。你能建议我用什么来代替它吗?

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

导入 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());
}
stack overflow org.mockito.internal.util.reflection.FieldSetter; deprecated in mockito-core 4.3.1
原文答案

答案:

作者头像

这是 Mockito 的内部类,你不应该依赖它。我最终改用了这个简单的工具:

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

}