万物皆可mock:@Value的 Mock方式

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

你可能感兴趣的:(单元测试)