在Mockito中注入弹簧值


问题内容

我正在尝试为以下方法编写测试类

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值未加载到CustomService中。我在想是否有办法完成这项工作。

谢谢


问题答案:

您可以自动装配到mutator(设置器)中,而不仅仅是注释私有字段。然后,您也可以在测试类中使用该设置器。不需要将其公开,可以使用私有包,因为Spring仍然可以访问它,但是否则,只有您的测试可以进入那里(或同一包中的其他代码)。

@Value("#{myProp['custom.url']}")
String setUrl( final String url ) {
    this.url  = url;
}

我不喜欢仅仅为了测试而自动进行不同的连接(与我的代码库相比),但是从测试中更改被测类的选择简直是邪恶的。