org.mockito.internal.util.reflection.FieldSeter;mockito核心4.3



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

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

导入org.mockito.internal.util.reflection.FieldSeter;

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

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

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

最新更新