Spring: unit and integration tests

前端 未结 4 587
北恋
北恋 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条回答
  •  无人及你
    2020-12-30 13:18

    I'd go with this version:

    ContextConfiguration(locations = { "/my_spring_test.xml" })
    public abstract class AbstractMyTestCase extends AbstractJUnit4SpringContextTests
    

    and in my_spring_test.xml, I'd use the PropertyPlaceHolderConfigurer mechanism.

    Example for JPA:

    
    
    
        
        
        
        
    
    
    
        
        
        
        
    
        
        
        
    
        
    
    

    Now all you need to do is have different versions of test.properties on the class path for in-memory and real integration tests (and of course the respective driver classes need to be present). You can even set system properties to overwrite the property values.


    If you want to prepare this with maven, you will find that copying files with maven is not trivial. You will need a way to execute code, the standard choices being the maven-antrun-plugin and gmaven-maven-plugin.

    Either way: have two configuration files, e.g. in src/main/config and add two plugin executions, one in phase generate-test-resources and one in phase pre-integration-test. Here's the GMaven version:

    
        org.codehaus.gmaven
        gmaven-plugin
        1.3
        
            
                pre-integration-test
                
                    execute
                
                
                
                new File(
                   pom.build.testOutputDirectory,
                   "test.properties"
                ).text = new File(
                           pom.basedir,
                           "src/main/config/int-test.properties"
                ).text;
                
                
            
            
                generate-test-resources
                
                    execute
                
                
                
                new File(
                   pom.build.testOutputDirectory,
                   "test.properties"
                ).text = new File(
                           pom.basedir,
                           "src/main/config/memory-test.properties"
                ).text;
                
                
            
        
    
    

提交回复
热议问题