【问题标题】:In mvn test, Spring-test throws sql script errors in mvn testmvn test中,spring-test在mvn test中抛出sql脚本错误
【发布时间】:2017-10-31 13:01:07
【问题描述】:

我有三个测试用例。当通过 RunAs > JUnit 和 mvn 单独的测试用例运行单独运行时,它们每个都成功执行。但是当我对所有三个一起运行 mvn test 时,前两个测试用例正确执行,第三个测试用例因 SQL 脚本错误而失败(表已经存在......)。

我的测试用例片段:

@DirtiesContext(classMode = 

DirtiesContext.ClassMode.AFTER_EACH_TEST_METHOD)
@TestExecutionListeners(DirtiesContextTestExecutionListener.class)
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = { "/blueReport-ItemProcessor-test-context.xml" })
public class BlueReportItemProcessorUnitTest {


@Qualifier("jdbcTemplate")
@Autowired
private JdbcTemplate jdbcTemplate;

@Qualifier("jdbcTemplateBMS")
@Autowired
private JdbcTemplate jdbcTemplateBMS;

@Autowired
private CountryExclusionDAO countryExclusionDAO;

@Autowired
private BMSReportDAO bmsReportDAO;

@Autowired
private MappingFileDao mappingFileDAO;

// getting cached list of countries that needs to be skipped
private SimpleCacheManager cacheManager = SimpleCacheManager.getInstance();


// This is what we're going to test here
@Autowired
private BlueReportItemProcessor blueReportItemProcessor;

// Static test variables
private static String test_AccountId = "ACCT1";
private static String test_ProjectId = "PROJ1";
private static String test_ContractNbr = "CTR057";
private static String test_ChannelName = "CHANNEL5";
private static String test_ChannelNameBR = "For Our BR clients";
private static String test_ChannelNameIN = "This channel is for IN";
private static String test_Country = "821";  // Excluded country
private static String test_CountryName = "Russia";


@Before
public void setUp() {

    // Setup Account map data first
    jdbcTemplate.update("DELETE from ACCOUNT_MAP");
    jdbcTemplate.update("INSERT INTO ACCOUNT_MAP(EXTERNALKEY, PROJECTID, EXTERNALSOURCE, CONTROLGROUP) VALUES('ACCT1', 'PROJ1', 'TESTCASE','GRP1')");

    // Setup BMS Shadow data next
    jdbcTemplate.update("DELETE from SHADOW_BMS");
    jdbcTemplate.update("INSERT INTO SHADOW_BMS(PROJ_TYP_CD, SYS_CD, STAT_CK_CD, EXTRNL_KEY_CD, EXTRNL_SYS_CD, CNTRCT_NUM, PROJ_NUM, CNTRCT_LINE_ITM, CUST_NUM, CUST_CNTL_NUM, CUST_NM, CHRG_CD, PRDCT_ID, BILNG_CRNCY_CD, BILNG_ISO_CRNCY_CD, BILNG_CRNCY_DCM_NUM, CFTS_CRNCY_EXCH_RT, CFTS_CRNCY_EXCH_RT_EXPIR_DT, CHRG_CRNCY_CD, CHRG_ISO_CRNCY_CD, CTRY_CD, CMPNY_CD, OFFERING_CD, CNTL_GRP_CD) VALUES('NEW', 'GO', 'ONE', 'ACCT1', 'TESTCASE', 'CTR057', 'PROJNUM1', 14, 'C293', '004', 'Fozzies Rubber Chicken Factory', '923D', '9207-908', null, null, 0, 0, null, null, null, 'USA', 'IBM', 'GOLD-BAR', 'ESKIMO') ");

    //invoke CountryExclusionDAO to put all the countries in the exclusion list
    Map<String,String> countryExclusionsMap = countryExclusionDAO.getAllCountryExclusions();
    cacheManager.put("countryExclusionsMap", countryExclusionsMap);

    //for getting cached list of rows from BMSIW
    cacheManager.put("bmsReportDAO", bmsReportDAO);

    //for getting account mappings
    cacheManager.put("mappingFileDAO", mappingFileDAO);

}

/**
 * Test the Country Exclusion Logic
 */
@Test
public void testCountryExclusion821() {

    // This setup tests the originating country skipping logic
    BlueReport testBlueReport = new BlueReport();
    testBlueReport.setAccount_id(test_AccountId);
    testBlueReport.setProject_id(test_ProjectId);
    testBlueReport.setContractNbr(test_ContractNbr);
    testBlueReport.setChannel_name(test_ChannelName);
    testBlueReport.setIbm_country_num(test_Country);
    testBlueReport.setIbm_country_name(test_CountryName);

    BlueReport brOut = null;

    // Invoke the Processor
    try {
        brOut =  blueReportItemProcessor.process(testBlueReport);
        assertTrue("Expected status=Skipped", brOut.getStatus().contains(Status.SKIPPED.toString()));
    } catch (Exception e) {
        Assert.fail("blueReportItemProcessor caught an unexpected exception in: " + e.getCause());
    }

}

这是部分 mvn test -X 输出:

[DEBUG] Adding to surefire test classpath: C:\Users\IBM_ADMIN\.m2\repository\org\apache\maven\surefire\surefire-junit4\2.12.4\surefire-junit4-2.12.4.jar Scope
[DEBUG] Adding to surefire test classpath: C:\Users\IBM_ADMIN\.m2\repository\org\apache\maven\surefire\surefire-api\2.12.4\surefire-api-2.12.4.jar Scope: test
[DEBUG] test classpath classpath:
[DEBUG]   C:\bluecost\target\test-classes
[DEBUG]   C:\bluecost\target\classes
[DEBUG]   C:\Users\IBM_ADMIN\.m2\repository\org\springframework\spring-core\4.3.12.RELEASE\spring-core-4.3.12.RELEASE.jar
[DEBUG]   C:\Users\IBM_ADMIN\.m2\repository\commons-logging\commons-logging\1.2\commons-logging-1.2.jar
[DEBUG]   C:\Users\IBM_ADMIN\.m2\repository\org\springframework\spring-jdbc\4.3.12.RELEASE\spring-jdbc-4.3.12.RELEASE.jar
[DEBUG]   C:\Users\IBM_ADMIN\.m2\repository\org\springframework\spring-beans\4.3.12.RELEASE\spring-beans-4.3.12.RELEASE.jar
[DEBUG]   C:\Users\IBM_ADMIN\.m2\repository\org\springframework\spring-tx\4.3.12.RELEASE\spring-tx-4.3.12.RELEASE.jar
[DEBUG]   C:\Users\IBM_ADMIN\.m2\repository\org\springframework\spring-test\4.3.12.RELEASE\spring-test-4.3.12.RELEASE.jar
[DEBUG]   C:\Users\IBM_ADMIN\.m2\repository\org\springframework\batch\spring-batch-test\2.2.0.RELEASE\spring-batch-test-2.2.0.RELEASE.jar
[DEBUG]   C:\Users\IBM_ADMIN\.m2\repository\commons-io\commons-io\1.4\commons-io-1.4.jar
[DEBUG]   C:\Users\IBM_ADMIN\.m2\repository\commons-collections\commons-collections\3.2\commons-collections-3.2.jar
[DEBUG]   C:\Users\IBM_ADMIN\.m2\repository\org\springframework\batch\spring-batch-core\3.0.8.RELEASE\spring-batch-core-3.0.8.RELEASE.jar
[DEBUG]   C:\Users\IBM_ADMIN\.m2\repository\com\ibm\jbatch\com.ibm.jbatch-tck-spi\1.0\com.ibm.jbatch-tck-spi-1.0.jar
[DEBUG]   C:\Users\IBM_ADMIN\.m2\repository\javax\batch\javax.batch-api\1.0\javax.batch-api-1.0.jar
[DEBUG]   C:\Users\IBM_ADMIN\.m2\repository\com\thoughtworks\xstream\xstream\1.4.7\xstream-1.4.7.jar
[DEBUG]   C:\Users\IBM_ADMIN\.m2\repository\xmlpull\xmlpull\1.1.3.1\xmlpull-1.1.3.1.jar
[DEBUG]   C:\Users\IBM_ADMIN\.m2\repository\xpp3\xpp3_min\1.1.4c\xpp3_min-1.1.4c.jar
[DEBUG]   C:\Users\IBM_ADMIN\.m2\repository\org\codehaus\jettison\jettison\1.2\jettison-1.2.jar
[DEBUG]   C:\Users\IBM_ADMIN\.m2\repository\org\springframework\spring-aop\4.0.5.RELEASE\spring-aop-4.0.5.RELEASE.jar
[DEBUG]   C:\Users\IBM_ADMIN\.m2\repository\aopalliance\aopalliance\1.0\aopalliance-1.0.jar
[DEBUG]   C:\Users\IBM_ADMIN\.m2\repository\org\springframework\spring-context\4.0.5.RELEASE\spring-context-4.0.5.RELEASE.jar
[DEBUG]   C:\Users\IBM_ADMIN\.m2\repository\org\springframework\spring-expression\4.0.5.RELEASE\spring-expression-4.0.5.RELEASE.jar
[DEBUG]   C:\Users\IBM_ADMIN\.m2\repository\org\springframework\batch\spring-batch-infrastructure\3.0.8.RELEASE\spring-batch-infrastructure-3.0.8.RELEASE.jar
[DEBUG]   C:\Users\IBM_ADMIN\.m2\repository\org\springframework\retry\spring-retry\1.1.0.RELEASE\spring-retry-1.1.0.RELEASE.jar
[DEBUG]   C:\Users\IBM_ADMIN\.m2\repository\mysql\mysql-connector-java\5.1.44\mysql-connector-java-5.1.44.jar
[DEBUG]   C:\Users\IBM_ADMIN\.m2\repository\com\ibm\db2\jcc\db2jcc_license_cisuz\10.1.0\db2jcc_license_cisuz-10.1.0.jar
[DEBUG]   C:\Users\IBM_ADMIN\.m2\repository\com\ibm\db2\jcc\db2jcc\10.1.0\db2jcc-10.1.0.jar
[DEBUG]   C:\Users\IBM_ADMIN\.m2\repository\junit\junit\4.12\junit-4.12.jar
[DEBUG]   C:\Users\IBM_ADMIN\.m2\repository\org\hamcrest\hamcrest-core\1.3\hamcrest-core-1.3.jar
[DEBUG]   C:\Users\IBM_ADMIN\.m2\repository\commons-dbcp\commons-dbcp\1.4\commons-dbcp-1.4.jar
[DEBUG]   C:\Users\IBM_ADMIN\.m2\repository\org\hsqldb\hsqldb\2.4.0\hsqldb-2.4.0.jar
[DEBUG]   C:\Users\IBM_ADMIN\.m2\repository\commons-pool\commons-pool\1.6\commons-pool-1.6.jar
[DEBUG] provider classpath classpath:
[DEBUG]   C:\Users\IBM_ADMIN\.m2\repository\org\apache\maven\surefire\surefire-junit4\2.12.4\surefire-junit4-2.12.4.jar
[DEBUG]   C:\Users\IBM_ADMIN\.m2\repository\org\apache\maven\surefire\surefire-api\2.12.4\surefire-api-2.12.4.jar

-------------------------------------------------------
 T E S T S
-------------------------------------------------------
Forking command line: cmd.exe /X /C ""C:\Program Files\Java\jdk1.8.0_60\jre\bin\java" -jar C:\bluecost\target\surefire\surefirebooter3090752069136285871.jar C
Running com.ibm.cio.cloud.cost.AppTest
Tests run: 1, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.028 sec
Running com.ibm.cio.cloud.cost.SimpleJobStepFunctionalTest
Tests run: 1, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 2.037 sec
Running com.ibm.cio.cloud.cost.unit.BlueReportItemProcessorUnitTest
[ERROR] TestContextManager - Caught exception while allowing TestExecutionListener [org.springframework.test.context.support.DependencyInjectionTestExecutionL
tion: Failed to load ApplicationContext>java.lang.IllegalStateException: Failed to load ApplicationContext
        at org.springframework.test.context.cache.DefaultCacheAwareContextLoaderDelegate.loadContext(DefaultCacheAwareContextLoaderDelegate.java:124)
        at org.springframework.test.context.support.DefaultTestContext.getApplicationContext(DefaultTestContext.java:83)
        at org.springframework.test.context.support.DependencyInjectionTestExecutionListener.injectDependencies(DependencyInjectionTestExecutionListener.java:
        at org.springframework.test.context.support.DependencyInjectionTestExecutionListener.prepareTestInstance(DependencyInjectionTestExecutionListener.java
        at org.springframework.test.context.TestContextManager.prepareTestInstance(TestContextManager.java:230)
        at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.createTest(SpringJUnit4ClassRunner.java:228)
        at org.springframework.test.context.junit4.SpringJUnit4ClassRunner$1.runReflectiveCall(SpringJUnit4ClassRunner.java:287)
        at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
        at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.methodBlock(SpringJUnit4ClassRunner.java:289)
        at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:247)
        at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:94)
        at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
        at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
        at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
        at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
        at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
        at org.springframework.test.context.junit4.statements.RunBeforeTestClassCallbacks.evaluate(RunBeforeTestClassCallbacks.java:61)
        at org.springframework.test.context.junit4.statements.RunAfterTestClassCallbacks.evaluate(RunAfterTestClassCallbacks.java:70)
        at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
        at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.run(SpringJUnit4ClassRunner.java:191)
        at org.apache.maven.surefire.junit4.JUnit4Provider.execute(JUnit4Provider.java:252)
        at org.apache.maven.surefire.junit4.JUnit4Provider.executeTestSet(JUnit4Provider.java:141)
        at org.apache.maven.surefire.junit4.JUnit4Provider.invoke(JUnit4Provider.java:112)
        at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
        at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
        at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
        at java.lang.reflect.Method.invoke(Method.java:497)
        at org.apache.maven.surefire.util.ReflectionUtils.invokeMethodWithArray(ReflectionUtils.java:189)
        at org.apache.maven.surefire.booter.ProviderFactory$ProviderProxy.invoke(ProviderFactory.java:165)
        at org.apache.maven.surefire.booter.ProviderFactory.invokeProvider(ProviderFactory.java:85)
        at org.apache.maven.surefire.booter.ForkedBooter.runSuitesInProcess(ForkedBooter.java:115)
        at org.apache.maven.surefire.booter.ForkedBooter.main(ForkedBooter.java:75)
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'org.springframework.jdbc.datasource.init.DataSourceInitiali
to execute SQL script statement #1 of class path resource [db/custom-db-assets.sql]: create table ACCOUNT_MAP( EXTERNALKEY VARCHAR(20) NOT NULL, PROJECTID VAR
ion: object name already exists: ACCOUNT_MAP in statement [create table ACCOUNT_MAP( EXTERNALKEY VARCHAR(20) NOT NULL, PROJECTID VARCHAR(20) NOT NULL, EXTERNA
        at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1628)
        at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:555)
        at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:483)
        at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:306)
        at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230)
        at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:302)
        at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:197)
        at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:761)
        at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:760)
        at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:482)
        at org.springframework.test.context.support.AbstractGenericContextLoader.loadContext(AbstractGenericContextLoader.java:128)
        at org.springframework.test.context.support.AbstractGenericContextLoader.loadContext(AbstractGenericContextLoader.java:60)
        at org.springframework.test.context.support.AbstractDelegatingSmartContextLoader.delegateLoading(AbstractDelegatingSmartContextLoader.java:108)
        at org.springframework.test.context.support.AbstractDelegatingSmartContextLoader.loadContext(AbstractDelegatingSmartContextLoader.java:251)
        at org.springframework.test.context.cache.DefaultCacheAwareContextLoaderDelegate.loadContextInternal(DefaultCacheAwareContextLoaderDelegate.java:98)
        at org.springframework.test.context.cache.DefaultCacheAwareContextLoaderDelegate.loadContext(DefaultCacheAwareContextLoaderDelegate.java:116)
        ... 31 more
Caused by: org.springframework.jdbc.datasource.init.ScriptStatementFailedException: Failed to execute SQL script statement #1 of class path resource [db/custo
ULL, CONTROLGROUP VARCHAR(10) NOT NULL ); nested exception is java.sql.SQLSyntaxErrorException: object name already exists: ACCOUNT_MAP in statement [create t
10) NOT NULL )]
        at org.springframework.jdbc.datasource.init.ScriptUtils.executeSqlScript(ScriptUtils.java:491)
        at org.springframework.jdbc.datasource.init.ResourceDatabasePopulator.populate(ResourceDatabasePopulator.java:238)

【问题讨论】:

  • 请添加您的测试类和配置,以便其他开发人员可以轻松找出问题
  • @JamesD Failed to execute SQL script 可能您有一些 data.sql 或其他一些 sql 源。您应该在创建新表之前删除以前的表。这可能只是一个设置问题,或者您可以在创建/跳过表创建之前调整您的 sql 以删除表
  • 是的——我的脚本首先删除表和触发器,然后再重新创建它们——这就是数据库初始化中发生的事情。它在单独运行时完美运行。这仅在 mvn 中对它们进行一一测试时不起作用。
  • 我相信这个问题已经记录在 spring-projects/spring-boot 问题 1712 中,并修复了 github.com/spring-projects/spring-boot/commit/…github.com/axibase/spring-boot/commit/… 我正在使用最新的 Spring 4.3 版本并且问题仍然存在。 ... :( 我能做什么?
  • 您是否有机会与 Maven 并行运行测试?

标签: spring maven junit spring-batch spring-test


【解决方案1】:

我不太确定您的数据库是如何构建的,我假设它是 dbUnit 或类似的。

您需要在测试的顶部添加类似以下内容,以确保在每次测试后删除 Spring 上下文。

@DirtiesContext(classMode = DirtiesContext.ClassMode.AFTER_EACH_TEST_METHOD)
@TestExecutionListeners(DirtiesContextTestExecutionListener.class)

可能还有其他 TestExecutionListener,完整示例请参见 here

【讨论】:

  • 感谢您的建议 - 不确定它的具体作用,但我在过去的示例中已经看到了。我的运行时数据库是 DB2 10.5,但测试用例使用的是 HSQLDB 内存数据库。数据源定义了数据库初始化部分,以正确的顺序拆除和重建所有数据库资产。似乎 create.sql 脚本在没有 delete.sql 脚本的情况下运行......
  • 将这两个语句添加到我的测试用例顶部之后,我现在在 setUp() 方法中得到 NullPointerExceptions - 当尝试引用应该已经自动装配的 jdbcUtils 对象时。我正在添加部分测试用例源和上下文文件。
  • 我分享的例子使用了一个内存数据库和dbUnit,你可以复制它。
【解决方案2】:

结果证明这是我的疏忽。我未能在创建脚本之前包含放置脚本:

<jdbc:initialize-database data-source="dataSource" ignore-failures="DROPS">
*** <jdbc:script location="${batch.business.schema.drop.script}"/>
    <jdbc:script location="${batch.business.schema.script}"/>
</jdbc:initialize-database>

【讨论】:

    猜你喜欢
    • 2018-09-26
    • 1970-01-01
    • 1970-01-01
    • 2018-07-16
    • 2021-06-26
    • 1970-01-01
    • 2011-07-02
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多