模拟弹簧值注入
2022-09-01 16:24:29
						我正在尝试为以下方法编写测试类
public class CustomServiceImpl implements CustomService {
    @Value("#{myProp['custom.url']}")
    private String url;
    @Autowire
    private DataService dataService;
我在类中的一个方法中使用注入的url值。为了测试这一点,我写了一个 junit 类
@RunWith(MockitoJUnitRunner.class)
@ContextConfiguration(locations = { "classpath:applicationContext-test.xml" })
public CustomServiceTest{
    private CustomService customService;
    @Mock
    private DataService dataService;
    @Before
    public void setup() {
        customService = new CustomServiceImpl();
        Setter.set(customService, "dataService", dataService);
    }    
    ...
}
public class Setter {
    public static void set(Object obj, String fieldName, Object value) throws Exception {
        Field field = obj.getClass().getDeclaredField(fieldName);
        field.setAccessible(true);
        field.set(obj, value);
    }
}
在 applicationContext-test 中.xml我正在加载属性文件
    <util:properties id="myProp" location="myProp.properties"/>
但是,在运行测试时,url 值不会加载到自定义服务中。我想知道是否有办法完成这项工作。
谢谢