在Mockito中注入弹簧值 [英] Spring value injection in mockito

查看:106
本文介绍了在Mockito中注入弹簧值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm trying to write test class for the following method

public class CustomServiceImpl implements CustomService {
    @Value("#{myProp['custom.url']}")
    private String url;
    @Autowire
    private DataService dataService;

我在类中的一种方法中使用注入的url值. 为了测试这一点,我编写了一个junit类

I'm using the injected url value in one of the methods in the class. To test this i've written a junit class

@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中,我使用

In applicationContext-test.xml I'm loading the property file using

    <util:properties id="myProp" location="myProp.properties"/>

但是在运行测试时,URL值未加载到CustomService中. 我想知道是否有任何方法可以做到这一点.

But the url value is not getting loaded in the CustomService on running the test. I was wondering if there is anyway to get this done.

谢谢

推荐答案

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

You can autowire into a mutator (setter), rather than just annotating the private field. Then you can use that setter from your test class as well. No need to make it public, package private will do as Spring can still access it, but otherwise only your test can get in there (or other code in the same package).

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

我不喜欢只是为了测试而自动地(与我的代码库相比)自动装配,但是从测试中更改被测类的选择简直是不道德的.

I'm not a fan of autowiring differently (compared to my codebase) just for testing, but the alternative of changing the class under test, from the test, is simply unholy.

这篇关于在Mockito中注入弹簧值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆