Spring: unit and integration tests

前端 未结 4 568
北恋
北恋 2020-12-30 13:07

I\'m looking for best practices for setting up unit and integration tests using Spring.

I usually use 3 kind of tests:

  • \"real\" unit tests (no dependen
4条回答
  •  -上瘾入骨i
    2020-12-30 13:17

    I extended the GenericXmlContextLoader

    public class MyContextLoader extends GenericXmlContextLoader {

    and overrote the

    protected String[] generateDefaultLocations(Class clazz)

    method to collect the config file names of a directory which I can specify by a SystemProperty (-Dtest.config=).

    I also modified the follwowing method to NOT modify any locations

    @Override
    protected String[] modifyLocations(Class clazz, String... locations) {
        return locations;
    }
    

    I use this context loader like this

    @RunWith(SpringJUnit4ClassRunner.class)
    @ContextConfiguration(loader = MyContextLoader.class)
    public class Test { .... }
    

    Running the test with a SystemProperty indicating the source of the config files enables you now to use completely different configurations.

    The usage of a SystemProperty is of course only one strategy to specify the configuration location. You can do whatever you want in generateDefaultLocations().


    EDIT:

    This solution enables you to use complete different application context configurations (e.g. for mock objects) and not only different properties. You do not need a build step to deploy everything to your "classpath" location. My concrete implementation also used the users name as default to look for a configuration directory (src/test/resources/{user}) if no system property is given (makes it easy to maintain specific test environments for all developers on the project).

    The usage of the PropertyPlaceholder ist still possible and recommended.


    EDIT:

    Spring Version 3.1.0 will support XML profiles/Environment Abstraction which is similar to my solution and will enable the choice of configuration files for different environments/profiles.

提交回复
热议问题