开发者

Mocking config values when testing a class using spring

I am trying to test a class like

@Controller
public class FailureController {

    @Value("#{configValues.defaultRedirectUrl}")
    private String defaultRedirectUrl;
public FailureController (String defaultRedirectUrl) {
this.defaultRedirectUrl = defaultRedirectUrl;
}
...

The problem is that I can't test this class without creating a special constructor for test class (like above), which is eventually to initializes the defaultRedirectUrl in FailureController.

How can I test it without creating a constructor (that are to be come from spring context) during the test. My main objective is to initialize the values in FailureController without a constructor when running a test.

Is it possible in some way that spring context gets loaded during the test and initializes the fields in FailureController this is what i have been doing but its not working, defaultRedirectUrl remains null in FailureController.

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(location开发者_Python百科s = { "/applicationContext-test.xml" })
public class FailureControllerTest {
    @Autowired
    FailureController failureController;

applicationContext-test.xml

...
        <bean id="failureController" class="se.synergica.watchtower.controllers.FailureController">
        </bean>

        <import resource="spring-config-test.xml" />
    </beans>

thank you. al


I would create a separate applicationContext.xml file in your test-classpath (src/test/resources in standard projects). There I would set up a configValues object with dummy values. Your class under test should also be instanciated in that context.

Then load the test context like this in a junit test:

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("/applicationContext-test.xml")
public class MyTest {

    @Autowired
    private AClassToBeTest subject;

    //...perform test on subject
}

more on spring testing: http://static.springsource.org/spring/docs/3.0.x/reference/testing.html


These config properties usually come from .properties files - simply use a different properties file (with test values) in the unit test classpath

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜