在mvn test中,Spring-test在mvn test中抛出sql脚本错误

时间:2017-10-31 13:01:07

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

我有三个测试用例。当通过RunAs单独运行时,它们各自成功执行> JUnit和mvn个人测试用例运行。但是当我在所有三个上运行mvn测试时,前两个测试用例正确执行,第三个测试用例因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)

2 个答案:

答案 0 :(得分:0)

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

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

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

可能是其他TestExecutionListeners,请参阅here获取完整示例

答案 1 :(得分:0)

这对我来说是遗漏。我没有在创建脚本之前包含drop脚本:

pyserial