Mock 类型 注解定义:
@InjectMocks
private SearchController searchController;
@Value("${start_switch}")
private Boolean startSwitch;
Mock @value的实现方式:
ReflectionTestUtils.setField(searchController, "startSwitch", false);
实现的源代码如下:
@Nullable
public static Field findField(Class<?> clazz, @Nullable String name, @Nullable Class<?> type) {
Assert.notNull(clazz, "Class must not be null");
Assert.isTrue(name != null || type != null, "Either name or type of the field must be specified");
for(Class searchType = clazz; Object.class != searchType && searchType != null; searchType = searchType.getSuperclass()) {
Field[] fields = getDeclaredFields(searchType);
Field[] var5 = fields;
int var6 = fields.length;
for(int var7 = 0; var7 < var6; ++var7) {
Field field = var5[var7];
if ((name == null || name.equals(field.getName())) && (type == null || type.equals(field.getType()))) {
return field;
}
}
}
return null;
}
本文探讨了在单元测试中使用@Mock和@InjectMocks注解的方法,以及如何通过ReflectionTestUtils.setField来设定被mock对象的字段值。详细解析了setField方法的源代码实现,展示了其内部如何查找并设置指定类型的字段。
2142





