在 mvn 测试中,弹簧测试在 mvn 测试中抛出 sql 脚本错误



我有三个测试用例。 当通过 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 测试 -X 输出:

[DEBUG] Adding to surefire test classpath: C:UsersIBM_ADMIN.m2repositoryorgapachemavensurefiresurefire-junit42.12.4surefire-junit4-2.12.4.jar Scope
[DEBUG] Adding to surefire test classpath: C:UsersIBM_ADMIN.m2repositoryorgapachemavensurefiresurefire-api2.12.4surefire-api-2.12.4.jar Scope: test
[DEBUG] test classpath classpath:
[DEBUG]   C:bluecosttargettest-classes
[DEBUG]   C:bluecosttargetclasses
[DEBUG]   C:UsersIBM_ADMIN.m2repositoryorgspringframeworkspring-core4.3.12.RELEASEspring-core-4.3.12.RELEASE.jar
[DEBUG]   C:UsersIBM_ADMIN.m2repositorycommons-loggingcommons-logging1.2commons-logging-1.2.jar
[DEBUG]   C:UsersIBM_ADMIN.m2repositoryorgspringframeworkspring-jdbc4.3.12.RELEASEspring-jdbc-4.3.12.RELEASE.jar
[DEBUG]   C:UsersIBM_ADMIN.m2repositoryorgspringframeworkspring-beans4.3.12.RELEASEspring-beans-4.3.12.RELEASE.jar
[DEBUG]   C:UsersIBM_ADMIN.m2repositoryorgspringframeworkspring-tx4.3.12.RELEASEspring-tx-4.3.12.RELEASE.jar
[DEBUG]   C:UsersIBM_ADMIN.m2repositoryorgspringframeworkspring-test4.3.12.RELEASEspring-test-4.3.12.RELEASE.jar
[DEBUG]   C:UsersIBM_ADMIN.m2repositoryorgspringframeworkbatchspring-batch-test2.2.0.RELEASEspring-batch-test-2.2.0.RELEASE.jar
[DEBUG]   C:UsersIBM_ADMIN.m2repositorycommons-iocommons-io1.4commons-io-1.4.jar
[DEBUG]   C:UsersIBM_ADMIN.m2repositorycommons-collectionscommons-collections3.2commons-collections-3.2.jar
[DEBUG]   C:UsersIBM_ADMIN.m2repositoryorgspringframeworkbatchspring-batch-core3.0.8.RELEASEspring-batch-core-3.0.8.RELEASE.jar
[DEBUG]   C:UsersIBM_ADMIN.m2repositorycomibmjbatchcom.ibm.jbatch-tck-spi1.0com.ibm.jbatch-tck-spi-1.0.jar
[DEBUG]   C:UsersIBM_ADMIN.m2repositoryjavaxbatchjavax.batch-api1.0javax.batch-api-1.0.jar
[DEBUG]   C:UsersIBM_ADMIN.m2repositorycomthoughtworksxstreamxstream1.4.7xstream-1.4.7.jar
[DEBUG]   C:UsersIBM_ADMIN.m2repositoryxmlpullxmlpull1.1.3.1xmlpull-1.1.3.1.jar
[DEBUG]   C:UsersIBM_ADMIN.m2repositoryxpp3xpp3_min1.1.4cxpp3_min-1.1.4c.jar
[DEBUG]   C:UsersIBM_ADMIN.m2repositoryorgcodehausjettisonjettison1.2jettison-1.2.jar
[DEBUG]   C:UsersIBM_ADMIN.m2repositoryorgspringframeworkspring-aop4.0.5.RELEASEspring-aop-4.0.5.RELEASE.jar
[DEBUG]   C:UsersIBM_ADMIN.m2repositoryaopallianceaopalliance1.0aopalliance-1.0.jar
[DEBUG]   C:UsersIBM_ADMIN.m2repositoryorgspringframeworkspring-context4.0.5.RELEASEspring-context-4.0.5.RELEASE.jar
[DEBUG]   C:UsersIBM_ADMIN.m2repositoryorgspringframeworkspring-expression4.0.5.RELEASEspring-expression-4.0.5.RELEASE.jar
[DEBUG]   C:UsersIBM_ADMIN.m2repositoryorgspringframeworkbatchspring-batch-infrastructure3.0.8.RELEASEspring-batch-infrastructure-3.0.8.RELEASE.jar
[DEBUG]   C:UsersIBM_ADMIN.m2repositoryorgspringframeworkretryspring-retry1.1.0.RELEASEspring-retry-1.1.0.RELEASE.jar
[DEBUG]   C:UsersIBM_ADMIN.m2repositorymysqlmysql-connector-java5.1.44mysql-connector-java-5.1.44.jar
[DEBUG]   C:UsersIBM_ADMIN.m2repositorycomibmdb2jccdb2jcc_license_cisuz10.1.0db2jcc_license_cisuz-10.1.0.jar
[DEBUG]   C:UsersIBM_ADMIN.m2repositorycomibmdb2jccdb2jcc10.1.0db2jcc-10.1.0.jar
[DEBUG]   C:UsersIBM_ADMIN.m2repositoryjunitjunit4.12junit-4.12.jar
[DEBUG]   C:UsersIBM_ADMIN.m2repositoryorghamcresthamcrest-core1.3hamcrest-core-1.3.jar
[DEBUG]   C:UsersIBM_ADMIN.m2repositorycommons-dbcpcommons-dbcp1.4commons-dbcp-1.4.jar
[DEBUG]   C:UsersIBM_ADMIN.m2repositoryorghsqldbhsqldb2.4.0hsqldb-2.4.0.jar
[DEBUG]   C:UsersIBM_ADMIN.m2repositorycommons-poolcommons-pool1.6commons-pool-1.6.jar
[DEBUG] provider classpath classpath:
[DEBUG]   C:UsersIBM_ADMIN.m2repositoryorgapachemavensurefiresurefire-junit42.12.4surefire-junit4-2.12.4.jar
[DEBUG]   C:UsersIBM_ADMIN.m2repositoryorgapachemavensurefiresurefire-api2.12.4surefire-api-2.12.4.jar
-------------------------------------------------------
 T E S T S
-------------------------------------------------------
Forking command line: cmd.exe /X /C ""C:Program FilesJavajdk1.8.0_60jrebinjava" -jar C:bluecosttargetsurefiresurefirebooter3090752069136285871.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)

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

在测试的顶部,你需要像下面这样的东西,以确保在每次测试后删除Spring上下文。

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

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

事实证明,这是我的疏忽。我未能在创建脚本之前包含删除脚本:

<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>

最新更新