Testing with Spring and Maven: applicationContext

前端 未结 9 1559
-上瘾入骨i
-上瘾入骨i 2020-12-13 04:04

Seems that question old as world, but I still can\'t find out the solution..

I\'m trying to run simple test:

@RunWith(SpringJUnit4ClassRunner.class)
         


        
9条回答
  •  再見小時候
    2020-12-13 04:44

    UPDATED: Actually in my case the problem was in Compile on Save option enabled. I use Netbeans, and the option was set to For test execution only. This value compiles changed files and replaces resources with new files. However, due to usage of application resources additionally to test resources, For test execution only produces incorrectly generated resources in target folder.

    Changing Compile on Save=For test execution only

    to Compile on Save=Disable fixes the problem.

    The text below is also correct, but sometimes does not work. It was working only till I restarted Netbeans IDE. However, the details of the reason of the problem are correct, hence, I prefer to leave the test.


    OLD: In my situation I have appContext-test.xml in src/main/resources. When I change any code and launch one unit test (not all of them) it recompiles and correctly executed. But if I launch same unit test again it is failed with the java.lang.IllegalStateException: Failed to load ApplicationContext.

    I have changed pom.xml from

    
        
            
                ${project.basedir}/src/main/resources
                true
            
        
        
            
                ${project.basedir}/src/test/java/resources
                true
            
        
    
    

    to

    
        
            
                ${project.basedir}/src/main/resources
                true
            
        
        
            
                ${project.basedir}/src/main/resources
                true
            
            
                ${project.basedir}/src/test/java/resources
                true
            
        
    
    

    and now all work fine.

    The error was due to appContext-test.xml uses src/main/resources/my.properties file with a lot of variables like

    database.url = ${database.url}
    database.username = ${database.username}
    database.password = ${database.password}
    

    that are filled during a build. However, if you skip src/main/resources in testResource, then my.properties is added to target/classes/my.properties as is, i.g. without a substitution. This file of course breaks the context.

    PS: You can remove ${project.basedir}/ - it is my custom thing.

提交回复
热议问题