BATCH-1344: added JobRunnerTestUtils and deprecated the old AbstractJobTests

This commit is contained in:
dsyer
2009-11-29 13:06:19 +00:00
parent f272684152
commit 48218f8e55
71 changed files with 774 additions and 796 deletions

View File

@@ -1,13 +1,14 @@
<?xml version="1.0" encoding="UTF-8"?>
<beansProjectDescription>
<version>1</version>
<pluginVersion><![CDATA[2.1.0.v200808011800]]></pluginVersion>
<configSuffixes>
<configSuffix><![CDATA[xml]]></configSuffix>
</configSuffixes>
<enableImports><![CDATA[true]]></enableImports>
<configs>
</configs>
<configSets>
</configSets>
</beansProjectDescription>
<?xml version="1.0" encoding="UTF-8"?>
<beansProjectDescription>
<version>1</version>
<pluginVersion><![CDATA[2.2.8.200911091054-RELEASE]]></pluginVersion>
<configSuffixes>
<configSuffix><![CDATA[xml]]></configSuffix>
</configSuffixes>
<enableImports><![CDATA[true]]></enableImports>
<configs>
<config>src/test/resources/test-context.xml</config>
</configs>
<configSets>
</configSets>
</beansProjectDescription>

View File

@@ -27,7 +27,6 @@ import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.BeanInitializationException;
import org.springframework.beans.factory.DisposableBean;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.core.io.Resource;
import org.springframework.dao.DataAccessException;
import org.springframework.jdbc.core.JdbcTemplate;
@@ -36,7 +35,6 @@ import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.support.TransactionCallback;
import org.springframework.transaction.support.TransactionTemplate;
import org.springframework.util.Assert;
import org.springframework.util.ClassUtils;
import org.springframework.util.StringUtils;
/**
@@ -66,16 +64,6 @@ public class DataSourceInitializer implements InitializingBean, DisposableBean {
private static boolean initialized = false;
/**
* Main method as convenient entry point.
*
* @param args
*/
public static void main(String... args) {
new ClassPathXmlApplicationContext(ClassUtils.addResourcePathToPackagePath(DataSourceInitializer.class,
DataSourceInitializer.class.getSimpleName() + "-context.xml"));
}
/**
* @throws Throwable
* @see java.lang.Object#finalize()

View File

@@ -24,18 +24,21 @@ import org.springframework.batch.core.BatchStatus;
import org.springframework.batch.core.JobExecution;
import org.springframework.batch.core.JobInstance;
import org.springframework.batch.core.launch.JobOperator;
import org.springframework.batch.test.AbstractJobTests;
import org.springframework.batch.test.JobRunnerTestUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
@ContextConfiguration(locations = { "/launch-context.xml" })
@ContextConfiguration(locations = { "/test-context.xml" })
@RunWith(SpringJUnit4ClassRunner.class)
public class ExampleJobConfigurationTests extends AbstractJobTests {
public class ExampleJobConfigurationTests {
@Autowired
private JobOperator jobOperator;
@Autowired
private JobRunnerTestUtils jobRunnerUtils;
/**
* Create a unique job instance and check it's execution completes
* successfully - uses the convenience methods provided by the testing
@@ -44,7 +47,7 @@ public class ExampleJobConfigurationTests extends AbstractJobTests {
@Test
public void testLaunchJob() throws Exception {
JobExecution jobExecution = launchJob(getUniqueJobParameters());
JobExecution jobExecution = jobRunnerUtils.launchJob(jobRunnerUtils.getUniqueJobParameters());
assertEquals(BatchStatus.COMPLETED, jobExecution.getStatus());
}
@@ -56,7 +59,7 @@ public class ExampleJobConfigurationTests extends AbstractJobTests {
public void testLaunchByJobOperator() throws Exception {
// assumes the job has a JobIncrementer set
long jobExecutionId = jobOperator.startNextInstance(getJob().getName());
long jobExecutionId = jobOperator.startNextInstance(jobRunnerUtils.getJob().getName());
// no need to wait for job completion in this case, the job is launched
// synchronously

View File

@@ -0,0 +1,13 @@
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-2.5.xsd">
<import resource="classpath*:/launch-context.xml"/>
<context:annotation-config/>
<bean class="org.springframework.batch.test.JobRunnerTestUtils"/>
</beans>

View File

@@ -1,4 +1,4 @@
#Tue Sep 22 12:31:29 BST 2009
#Sun Nov 29 12:58:26 GMT 2009
eclipse.preferences.version=1
org.springframework.ide.eclipse.core.builders.enable.aopreferencemodelbuilder=true
org.springframework.ide.eclipse.core.builders.enable.beanmetadatabuilder=true
@@ -52,6 +52,7 @@ org.springframework.ide.eclipse.core.validator.rule.enable.com.springsource.sts.
org.springframework.ide.eclipse.core.validator.rule.enable.com.springsource.sts.server.quickfix.importLibraryVersionRule-com.springsource.sts.server.quickfix.manifestvalidator=false
org.springframework.ide.eclipse.core.validator.rule.enable.com.springsource.sts.server.quickfix.importPackageVersionRule-com.springsource.sts.server.quickfix.manifestvalidator=false
org.springframework.ide.eclipse.core.validator.rule.enable.com.springsource.sts.server.quickfix.requireBundleVersionRule-com.springsource.sts.server.quickfix.manifestvalidator=false
org.springframework.ide.eclipse.core.validator.rule.enable.org.springframework.ide.eclipse.beans.core.autowire.autowire-org.springframework.ide.eclipse.beans.core.beansvalidator=false
org.springframework.ide.eclipse.core.validator.rule.enable.org.springframework.ide.eclipse.beans.core.beanAlias-org.springframework.ide.eclipse.beans.core.beansvalidator=true
org.springframework.ide.eclipse.core.validator.rule.enable.org.springframework.ide.eclipse.beans.core.beanClass-org.springframework.ide.eclipse.beans.core.beansvalidator=true
org.springframework.ide.eclipse.core.validator.rule.enable.org.springframework.ide.eclipse.beans.core.beanConstructorArgument-org.springframework.ide.eclipse.beans.core.beansvalidator=true
@@ -64,6 +65,7 @@ org.springframework.ide.eclipse.core.validator.rule.enable.org.springframework.i
org.springframework.ide.eclipse.core.validator.rule.enable.org.springframework.ide.eclipse.beans.core.methodOverride-org.springframework.ide.eclipse.beans.core.beansvalidator=true
org.springframework.ide.eclipse.core.validator.rule.enable.org.springframework.ide.eclipse.beans.core.parsingProblems-org.springframework.ide.eclipse.beans.core.beansvalidator=true
org.springframework.ide.eclipse.core.validator.rule.enable.org.springframework.ide.eclipse.beans.core.requiredProperty-org.springframework.ide.eclipse.beans.core.beansvalidator=false
org.springframework.ide.eclipse.core.validator.rule.enable.org.springframework.ide.eclipse.beans.core.toolAnnotation-org.springframework.ide.eclipse.beans.core.beansvalidator=false
org.springframework.ide.eclipse.core.validator.rule.enable.org.springframework.ide.eclipse.core.springClasspath-org.springframework.ide.eclipse.core.springvalidator=false
org.springframework.ide.eclipse.core.validator.rule.enable.org.springframework.ide.eclipse.webflow.core.validation.action-org.springframework.ide.eclipse.webflow.core.validator=true
org.springframework.ide.eclipse.core.validator.rule.enable.org.springframework.ide.eclipse.webflow.core.validation.actionstate-org.springframework.ide.eclipse.webflow.core.validator=true

View File

@@ -1,7 +1,7 @@
<?xml version="1.0" encoding="UTF-8"?>
<beansProjectDescription>
<version>1</version>
<pluginVersion><![CDATA[2.2.7.200910202224-RELEASE]]></pluginVersion>
<pluginVersion><![CDATA[2.2.8.200911091054-RELEASE]]></pluginVersion>
<configSuffixes>
<configSuffix><![CDATA[xml]]></configSuffix>
</configSuffixes>
@@ -45,37 +45,22 @@
<config>src/main/resources/jobs/hibernateJob.xml</config>
<config>src/main/resources/jobs/iosample/jpa.xml</config>
<config>src/main/resources/jobs/iosample/ibatis.xml</config>
<config>src/test/resources/org/springframework/batch/sample/JobOperatorFunctionalTests-context.xml</config>
<config>src/test/resources/org/springframework/batch/sample/BeanWrapperMapperSampleJobFunctionalTests-context.xml</config>
<config>src/test/resources/org/springframework/batch/sample/CompositeItemWriterSampleFunctionalTests-context.xml</config>
<config>src/test/resources/org/springframework/batch/sample/CustomerFilterJobFunctionalTests-context.xml</config>
<config>src/test/resources/org/springframework/batch/sample/DatabaseShutdownFunctionalTests-context.xml</config>
<config>src/test/resources/org/springframework/batch/sample/DelegatingJobFunctionalTests-context.xml</config>
<config>src/test/resources/org/springframework/batch/sample/FootballJobFunctionalTests-context.xml</config>
<config>src/test/resources/org/springframework/batch/sample/GracefulShutdownFunctionalTests-context.xml</config>
<config>src/test/resources/org/springframework/batch/sample/HeaderFooterSampleFunctionalTests-context.xml</config>
<config>src/test/resources/org/springframework/batch/sample/HibernateFailureJobFunctionalTests-context.xml</config>
<config>src/test/resources/org/springframework/batch/sample/domain/trade/internal/JdbcCustomerDebitDaoTests-context.xml</config>
<config>src/main/resources/jobs/loopFlowSample.xml</config>
<config>src/test/resources/org/springframework/batch/sample/MultilineJobFunctionalTests-context.xml</config>
<config>src/test/resources/org/springframework/batch/sample/MultilineOrderJobFunctionalTests-context.xml</config>
<config>src/test/resources/org/springframework/batch/sample/ParallelJobFunctionalTests-context.xml</config>
<config>src/test/resources/org/springframework/batch/sample/RestartFunctionalTests-context.xml</config>
<config>src/test/resources/org/springframework/batch/sample/RetrySampleFunctionalTests-context.xml</config>
<config>src/test/resources/org/springframework/batch/sample/common/StagingItemReaderTests-context.xml</config>
<config>src/test/resources/org/springframework/batch/sample/common/StagingItemWriterTests-context.xml</config>
<config>src/test/resources/org/springframework/batch/sample/TradeJobFunctionalTests-context.xml</config>
<config>src/main/resources/jobs/multilineOrderValidator.xml</config>
<config>src/main/resources/jobs/restartFileSampleJob.xml</config>
<config>src/main/resources/jobs/taskletJob.xml</config>
<config>src/main/resources/org/springframework/batch/sample/football-job-context.xml</config>
<config>src/main/resources/jobs/groovyJob.xml</config>
<config>src/main/resources/jobs/iosample/jdbcPaging.xml</config>
<config>src/test/resources/org/springframework/batch/sample/GroovyJobFunctionalTests-context.xml</config>
<config>src/test/resources/org/springframework/batch/sample/TaskletJobFunctionalTests-context.xml</config>
<config>src/main/resources/jobs/partitionJdbcJob.xml</config>
<config>src/main/resources/jobs/jobStepSample.xml</config>
<config>src/main/resources/jobs/partitionFileJob.xml</config>
<config>src/test/resources/org/springframework/batch/sample/common/ColumnRangePartitionerTests-context.xml</config>
<config>src/test/resources/job-runner-context.xml</config>
<config>src/test/resources/org/springframework/batch/sample/JobStepFunctionalTests-context.xml</config>
</configs>
<configSets>
<configSet>

View File

@@ -1,102 +0,0 @@
/*
* Copyright 2006-2007 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.batch.sample;
import static org.junit.Assert.assertEquals;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.junit.Assert;
import org.junit.Test;
import org.springframework.batch.core.BatchStatus;
import org.springframework.batch.core.Job;
import org.springframework.batch.core.JobExecution;
import org.springframework.batch.core.JobParameters;
import org.springframework.batch.core.launch.JobLauncher;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
/**
* Abstract unit test for running functional tests by getting context locations
* for both the container and configuration separately and having them auto
* wired in by type. This allows the two to be completely separated, and remove
* any 'configuration coupling' between the two.
*
* @author Lucas Ward
*
*/
public abstract class AbstractBatchLauncherTests implements ApplicationContextAware {
/** Logger */
protected final Log logger = LogFactory.getLog(getClass());
protected ApplicationContext applicationContext;
private JobLauncher launcher;
private JobExecution jobExecution;
private Job job;
private JobParameters jobParameters = new JobParameters();
public void setApplicationContext(ApplicationContext applicationContext) {
this.applicationContext = applicationContext;
}
@Autowired
public void setLauncher(JobLauncher bootstrap) {
this.launcher = bootstrap;
}
@Autowired
public void setJob(Job job) {
this.job = job;
}
public JobExecution getJobExecution() {
return jobExecution;
}
public Job getJob() {
return job;
}
protected String getJobName() {
return job.getName();
}
public void setJobParameters(JobParameters jobParameters) {
this.jobParameters = jobParameters;
}
@Test
public void testLaunchJob() throws Exception {
jobExecution = getLauncher().run(job, jobParameters);
Assert.assertEquals(BatchStatus.COMPLETED, jobExecution.getStatus());
assertEquals(BatchStatus.COMPLETED, jobExecution.getStatus());
}
/**
* Public getter for the launcher.
* @return the launcher
*/
protected JobLauncher getLauncher() {
return launcher;
}
}

View File

@@ -1,140 +0,0 @@
package org.springframework.batch.sample;
import static org.junit.Assert.assertEquals;
import java.math.BigDecimal;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import javax.sql.DataSource;
import org.springframework.batch.sample.domain.trade.internal.CustomerCreditIncreaseProcessor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.RowCallbackHandler;
import org.springframework.jdbc.core.simple.ParameterizedRowMapper;
import org.springframework.jdbc.core.simple.SimpleJdbcTemplate;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.support.TransactionCallback;
import org.springframework.transaction.support.TransactionTemplate;
/**
* Test case for jobs that are expected to update customer credit value by fixed
* amount.
*
* @author Robert Kasanicky
* @author Dave Syer
*/
public abstract class AbstractCustomerCreditIncreaseTests extends AbstractValidatingBatchLauncherTests {
protected SimpleJdbcTemplate simpleJdbcTemplate;
protected PlatformTransactionManager transactionManager;
private static final BigDecimal CREDIT_INCREASE = CustomerCreditIncreaseProcessor.FIXED_AMOUNT;
private static String[] customers = { "INSERT INTO CUSTOMER (id, version, name, credit) VALUES (1, 0, 'customer1', 100000)",
"INSERT INTO CUSTOMER (id, version, name, credit) VALUES (2, 0, 'customer2', 100000)",
"INSERT INTO CUSTOMER (id, version, name, credit) VALUES (3, 0, 'customer3', 100000)",
"INSERT INTO CUSTOMER (id, version, name, credit) VALUES (4, 0, 'customer4', 100000)"};
private static String DELETE_CUSTOMERS = "DELETE FROM CUSTOMER";
private static final String ALL_CUSTOMERS = "select * from CUSTOMER order by ID";
private static final String CREDIT_COLUMN = "CREDIT";
protected static final String ID_COLUMN = "ID";
private List<BigDecimal> creditsBeforeUpdate;
@Autowired
public void setDataSource(DataSource dataSource) {
this.simpleJdbcTemplate = new SimpleJdbcTemplate(dataSource);
}
@Autowired
public void setTransactionManager(PlatformTransactionManager transactionManager) {
this.transactionManager = transactionManager;
}
/**
* All customers have the same credit
*/
@SuppressWarnings("unchecked")
protected void validatePreConditions() throws Exception {
super.validatePreConditions();
ensureState();
creditsBeforeUpdate = (List<BigDecimal>) new TransactionTemplate(transactionManager).execute(new TransactionCallback() {
public Object doInTransaction(TransactionStatus status) {
return simpleJdbcTemplate.query(ALL_CUSTOMERS, new ParameterizedRowMapper<BigDecimal>() {
public BigDecimal mapRow(ResultSet rs, int rowNum) throws SQLException {
return rs.getBigDecimal(CREDIT_COLUMN);
}
});
}
});
}
/*
* Ensure the state of the database is accurate by delete all the contents of the
* customer table and reading the expected defaults.
*/
private void ensureState(){
new TransactionTemplate(transactionManager).execute(new TransactionCallback(){
public Object doInTransaction(TransactionStatus status) {
simpleJdbcTemplate.update(DELETE_CUSTOMERS);
for (String customer : customers) {
simpleJdbcTemplate.update(customer);
}
return null;
}
});
}
/**
* Credit was increased by CREDIT_INCREASE
*/
protected void validatePostConditions() throws Exception {
final List<BigDecimal> matches = new ArrayList<BigDecimal>();
new TransactionTemplate(transactionManager).execute(new TransactionCallback() {
public Object doInTransaction(TransactionStatus status) {
simpleJdbcTemplate.getJdbcOperations().query(ALL_CUSTOMERS, new RowCallbackHandler() {
private int i = 0;
public void processRow(ResultSet rs) throws SQLException {
final BigDecimal creditBeforeUpdate = creditsBeforeUpdate.get(i++);
final BigDecimal expectedCredit = creditBeforeUpdate.add(CREDIT_INCREASE);
if (expectedCredit.equals(rs.getBigDecimal(CREDIT_COLUMN))) {
matches.add(rs.getBigDecimal(ID_COLUMN));
}
}
});
return null;
}
});
assertEquals(getExpectedMatches(), matches.size());
checkMatches(matches);
}
protected void checkMatches(List<BigDecimal> matches) {
// no-op...
}
/**
* @return the expected number of matches in the updated credits.
*/
protected int getExpectedMatches() {
return creditsBeforeUpdate.size();
}
}

View File

@@ -1,57 +0,0 @@
/*
* Copyright 2006-2007 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.batch.sample;
import org.junit.Test;
import org.springframework.context.Lifecycle;
/**
* Abstract TestCase that automatically starts a Spring {@link Lifecycle} after
* obtaining it automatically via autowiring by type.
*
* This implemenation is based on JUnit4 and SpringJUnit4ClassRunner being used
* to provide autowiring. It should be noted that @ContextConfiguration must be
* specified for dependency injection to work properly.
*
* @author Lucas Ward
* @author Thomas Risberg
*
* @see org.springframework.test.context.junit4.SpringJUnit4ClassRunner
*/
public abstract class AbstractValidatingBatchLauncherTests extends AbstractBatchLauncherTests {
@Test
public void testLaunchJob() throws Exception {
validatePreConditions();
super.testLaunchJob();
validatePostConditions();
}
/**
* Make sure input data meets expectations
* @throws Exception any exception thrown
*/
protected void validatePreConditions() throws Exception {
}
/**
* Make sure job did what it was expected to do.
* @throws Exception any exception thrown
*/
protected abstract void validatePostConditions() throws Exception;
}

View File

@@ -16,17 +16,27 @@
package org.springframework.batch.sample;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.batch.test.JobRunnerTestUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration()
public class BeanWrapperMapperSampleJobFunctionalTests extends AbstractValidatingBatchLauncherTests {
@ContextConfiguration(locations = { "/simple-job-launcher-context.xml", "/jobs/beanWrapperMapperSampleJob.xml",
"/job-runner-context.xml" })
public class BeanWrapperMapperSampleJobFunctionalTests {
protected void validatePostConditions() {
// nothing to check, the job writes no output
@Autowired
private JobRunnerTestUtils jobRunnerUtils;
@Test
public void testJobLaunch() throws Exception {
jobRunnerUtils.launchJob();
}
}

View File

@@ -13,8 +13,10 @@ import java.util.List;
import javax.sql.DataSource;
import org.apache.commons.io.IOUtils;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.batch.sample.domain.trade.Trade;
import org.springframework.batch.test.JobRunnerTestUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.RowCallbackHandler;
import org.springframework.jdbc.core.simple.SimpleJdbcTemplate;
@@ -22,8 +24,8 @@ import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration()
public class CompositeItemWriterSampleFunctionalTests extends AbstractValidatingBatchLauncherTests {
@ContextConfiguration(locations = { "/simple-job-launcher-context.xml", "/jobs/compositeItemWriterSampleJob.xml", "/job-runner-context.xml" })
public class CompositeItemWriterSampleFunctionalTests {
private static final String GET_TRADES = "SELECT isin, quantity, price, customer FROM TRADE order by isin";
@@ -35,29 +37,29 @@ public class CompositeItemWriterSampleFunctionalTests extends AbstractValidating
private SimpleJdbcTemplate simpleJdbcTemplate;
private int activeRow = 0;
private int before;
@Autowired
private JobRunnerTestUtils jobRunnerUtils;
@Autowired
public void setDataSource(DataSource dataSource) {
this.simpleJdbcTemplate = new SimpleJdbcTemplate(dataSource);
}
@Override
protected void validatePreConditions() throws Exception {
simpleJdbcTemplate.update("DELETE from TRADE");
before = simpleJdbcTemplate.queryForInt("SELECT COUNT(*) from TRADE");
}
@Test
public void testJobLaunch() throws Exception {
simpleJdbcTemplate.update("DELETE from TRADE");
int before = simpleJdbcTemplate.queryForInt("SELECT COUNT(*) from TRADE");
jobRunnerUtils.launchJob();
@Override
protected void validatePostConditions() throws Exception {
checkOutputFile("target/test-outputs/CustomerReport1.txt");
checkOutputFile("target/test-outputs/CustomerReport2.txt");
checkOutputTable();
checkOutputTable(before);
}
private void checkOutputTable() {
private void checkOutputTable(int before) {
final List<Trade> trades = new ArrayList<Trade>() {
{
add(new Trade("UK21341EAH41", 211, new BigDecimal("31.11"), "customer1"));
@@ -71,8 +73,10 @@ public class CompositeItemWriterSampleFunctionalTests extends AbstractValidating
int after = simpleJdbcTemplate.queryForInt("SELECT COUNT(*) from TRADE");
assertEquals(before + 5, after);
simpleJdbcTemplate.getJdbcOperations().query(GET_TRADES, new RowCallbackHandler() {
private int activeRow = 0;
public void processRow(ResultSet rs) throws SQLException {
Trade trade = trades.get(activeRow++);

View File

@@ -32,7 +32,7 @@ import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.batch.core.JobExecution;
import org.springframework.batch.test.AbstractJobTests;
import org.springframework.batch.test.JobRunnerTestUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.RowCallbackHandler;
import org.springframework.jdbc.core.simple.SimpleJdbcTemplate;
@@ -40,8 +40,8 @@ import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration
public class CustomerFilterJobFunctionalTests extends AbstractJobTests {
@ContextConfiguration(locations = { "/simple-job-launcher-context.xml", "/jobs/customerFilterJob.xml", "/job-runner-context.xml" })
public class CustomerFilterJobFunctionalTests {
private static final String GET_CUSTOMERS = "select NAME, CREDIT from CUSTOMER order by NAME";
@@ -51,6 +51,9 @@ public class CustomerFilterJobFunctionalTests extends AbstractJobTests {
private SimpleJdbcTemplate simpleJdbcTemplate;
private Map<String, Double> credits = new HashMap<String, Double>();
@Autowired
private JobRunnerTestUtils jobRunnerUtils;
@Autowired
public void setDataSource(DataSource dataSource) {
this.simpleJdbcTemplate = new SimpleJdbcTemplate(dataSource);
@@ -76,7 +79,7 @@ public class CustomerFilterJobFunctionalTests extends AbstractJobTests {
@Test
public void testFilterJob() throws Exception {
JobExecution jobExecution = this.launchJob();
JobExecution jobExecution = jobRunnerUtils.launchJob();
customers = Arrays.asList(new Customer("customer1", (credits.get("customer1"))), new Customer("customer2",
(credits.get("customer2"))), new Customer("customer3", 100500), new Customer("customer4", credits

View File

@@ -16,14 +16,19 @@
package org.springframework.batch.sample;
import static org.junit.Assert.*;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.batch.core.BatchStatus;
import org.springframework.batch.core.JobExecution;
import org.springframework.batch.core.JobParameters;
import org.springframework.batch.core.launch.JobOperator;
import org.springframework.batch.test.JobRunnerTestUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
@@ -36,22 +41,22 @@ import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
*
*/
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration()
public class DatabaseShutdownFunctionalTests extends AbstractBatchLauncherTests {
@ContextConfiguration(locations = { "/simple-job-launcher-context.xml", "/jobs/infiniteLoopJob.xml", "/job-runner-context.xml" })
public class DatabaseShutdownFunctionalTests {
/** Logger */
protected final Log logger = LogFactory.getLog(getClass());
@Autowired
private JobOperator jobOperator;
@Autowired
public void setJobOperator(JobOperator jobOperator) {
this.jobOperator = jobOperator;
}
private JobRunnerTestUtils jobRunnerUtils;
@Test
public void testLaunchJob() throws Exception {
final JobParameters jobParameters = new JobParameters();
JobExecution jobExecution = getLauncher().run(getJob(), jobParameters);
JobExecution jobExecution = jobRunnerUtils.launchJob();
Thread.sleep(1000);

View File

@@ -3,20 +3,29 @@ package org.springframework.batch.sample;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.batch.sample.domain.person.PersonService;
import org.springframework.batch.test.JobRunnerTestUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration()
public class DelegatingJobFunctionalTests extends AbstractValidatingBatchLauncherTests {
@ContextConfiguration(locations = { "/simple-job-launcher-context.xml", "/jobs/delegatingJob.xml", "/job-runner-context.xml" })
public class DelegatingJobFunctionalTests {
@Autowired
private JobRunnerTestUtils jobRunnerUtils;
@Autowired
private PersonService personService;
protected void validatePostConditions() throws Exception {
@Test
public void testLaunchJob() throws Exception {
jobRunnerUtils.launchJob();
assertTrue(personService.getReturnedCount() > 0);
assertEquals(personService.getReturnedCount(), personService.getReceivedCount());

View File

@@ -4,15 +4,20 @@ import static org.junit.Assert.assertTrue;
import javax.sql.DataSource;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.batch.test.JobRunnerTestUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.simple.SimpleJdbcTemplate;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration()
public class FootballJobFunctionalTests extends AbstractValidatingBatchLauncherTests {
@ContextConfiguration(locations = { "/simple-job-launcher-context.xml", "/jobs/footballJob.xml", "/job-runner-context.xml" })
public class FootballJobFunctionalTests {
@Autowired
private JobRunnerTestUtils jobRunnerUtils;
private SimpleJdbcTemplate simpleJdbcTemplate;
@@ -21,18 +26,18 @@ public class FootballJobFunctionalTests extends AbstractValidatingBatchLauncherT
this.simpleJdbcTemplate = new SimpleJdbcTemplate(dataSource);
}
@Override
protected void validatePreConditions() throws Exception {
@Test
public void testLaunchJob() throws Exception {
simpleJdbcTemplate.update("DELETE FROM PLAYERS");
simpleJdbcTemplate.update("DELETE FROM GAMES");
simpleJdbcTemplate.update("DELETE FROM PLAYER_SUMMARY");
super.validatePreConditions();
}
@Override
protected void validatePostConditions() throws Exception {
jobRunnerUtils.launchJob();
int count = simpleJdbcTemplate.queryForInt("SELECT COUNT(*) from PLAYER_SUMMARY");
assertTrue(count > 0);
}
}

View File

@@ -20,12 +20,16 @@ import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.batch.core.BatchStatus;
import org.springframework.batch.core.JobExecution;
import org.springframework.batch.core.JobParameters;
import org.springframework.batch.core.JobParametersBuilder;
import org.springframework.batch.test.JobRunnerTestUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
@@ -37,17 +41,22 @@ import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
*
*/
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration()
public class GracefulShutdownFunctionalTests extends AbstractBatchLauncherTests {
@ContextConfiguration(locations = { "/simple-job-launcher-context.xml", "/jobs/infiniteLoopJob.xml", "/job-runner-context.xml" })
public class GracefulShutdownFunctionalTests {
/** Logger */
private final Log logger = LogFactory.getLog(getClass());
@Autowired
private JobRunnerTestUtils jobRunnerUtils;
@Test
@Override
public void testLaunchJob() throws Exception {
final JobParameters jobParameters = new JobParametersBuilder().addLong("timestamp", System.currentTimeMillis())
.toJobParameters();
JobExecution jobExecution = getLauncher().run(getJob(), jobParameters);
JobExecution jobExecution = jobRunnerUtils.launchJob(jobParameters);
Thread.sleep(1000);

View File

@@ -26,30 +26,29 @@ import org.apache.commons.io.FileUtils;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.batch.test.JobRunnerTestUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration()
public class GroovyJobFunctionalTests extends AbstractValidatingBatchLauncherTests {
@ContextConfiguration(locations = { "/simple-job-launcher-context.xml", "/jobs/groovyJob.xml",
"/job-runner-context.xml" })
public class GroovyJobFunctionalTests {
@Autowired
private JobRunnerTestUtils jobRunnerUtils;
@Before
public void removeOldData() throws IOException {
FileUtils.deleteDirectory(new File("target/groovyJob"));
}
@Test
public void testLaunchJob() throws Exception{
super.testLaunchJob();
public void testLaunchJob() throws Exception {
assertFalse(new File("target/groovyJob/output/files.zip").exists());
jobRunnerUtils.launchJob();
assertTrue(new File("target/groovyJob/output/files.zip").exists());
}
protected void validatePostConditions() {
assertTrue(new File("target/groovyJob/output/files.zip").exists());
}
protected void validatePreConditions() {
assertFalse(new File("target/groovyJob/output/files.zip").exists());
}
}

View File

@@ -1,22 +1,37 @@
package org.springframework.batch.sample;
import static org.junit.Assert.assertTrue;
import java.io.BufferedReader;
import java.io.FileReader;
import static org.junit.Assert.*;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.batch.test.JobRunnerTestUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.core.io.Resource;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration
public class HeaderFooterSampleFunctionalTests extends AbstractValidatingBatchLauncherTests {
@ContextConfiguration(locations = { "/simple-job-launcher-context.xml", "/jobs/headerFooterSample.xml", "/job-runner-context.xml" })
public class HeaderFooterSampleFunctionalTests {
@Override
protected void validatePostConditions() throws Exception {
Resource input = (Resource) applicationContext.getBean("inputResource", Resource.class);
Resource output = (Resource) applicationContext.getBean("outputResource", Resource.class);
@Autowired
@Qualifier("inputResource")
private Resource input;
@Autowired
@Qualifier("outputResource")
private Resource output;
@Autowired
private JobRunnerTestUtils jobRunnerUtils;
@Test
public void testJob() throws Exception {
jobRunnerUtils.launchJob();
BufferedReader inputReader = new BufferedReader(new FileReader(input.getFile()));
BufferedReader outputReader = new BufferedReader(new FileReader(output.getFile()));

View File

@@ -1,20 +1,35 @@
package org.springframework.batch.sample;
import static org.junit.Assert.*;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import java.math.BigDecimal;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import javax.sql.DataSource;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.batch.core.JobParameters;
import org.springframework.batch.core.JobParametersBuilder;
import org.springframework.batch.sample.domain.trade.internal.CustomerCreditIncreaseProcessor;
import org.springframework.batch.sample.domain.trade.internal.HibernateCreditDao;
import org.springframework.batch.test.JobRunnerTestUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.UncategorizedSQLException;
import org.springframework.jdbc.core.RowCallbackHandler;
import org.springframework.jdbc.core.simple.ParameterizedRowMapper;
import org.springframework.jdbc.core.simple.SimpleJdbcTemplate;
import org.springframework.orm.hibernate3.HibernateJdbcException;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.support.TransactionCallback;
import org.springframework.transaction.support.TransactionTemplate;
/**
* Test for HibernateJob - checks that customer credit has been updated to
@@ -23,30 +38,57 @@ import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
* @author Dave Syer
*/
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration()
public class HibernateFailureJobFunctionalTests extends AbstractCustomerCreditIncreaseTests {
@ContextConfiguration(locations = { "/simple-job-launcher-context.xml", "/hibernate-context.xml", "/jobs/hibernateJob.xml",
"/job-runner-context.xml" })
public class HibernateFailureJobFunctionalTests {
@Autowired
private HibernateCreditDao writer;
/**
* Public setter for the {@link HibernateCreditDao} property.
*
* @param writer
* the writer to set
*/
private SimpleJdbcTemplate simpleJdbcTemplate;
private PlatformTransactionManager transactionManager;
private static final BigDecimal CREDIT_INCREASE = CustomerCreditIncreaseProcessor.FIXED_AMOUNT;
private static String[] customers = { "INSERT INTO CUSTOMER (id, version, name, credit) VALUES (1, 0, 'customer1', 100000)",
"INSERT INTO CUSTOMER (id, version, name, credit) VALUES (2, 0, 'customer2', 100000)",
"INSERT INTO CUSTOMER (id, version, name, credit) VALUES (3, 0, 'customer3', 100000)",
"INSERT INTO CUSTOMER (id, version, name, credit) VALUES (4, 0, 'customer4', 100000)"};
private static String DELETE_CUSTOMERS = "DELETE FROM CUSTOMER";
private static final String ALL_CUSTOMERS = "select * from CUSTOMER order by ID";
private static final String CREDIT_COLUMN = "CREDIT";
protected static final String ID_COLUMN = "ID";
private List<BigDecimal> creditsBeforeUpdate;
@Autowired
public void setWriter(HibernateCreditDao writer) {
this.writer = writer;
private JobRunnerTestUtils jobRunnerUtils;
@Autowired
public void setDataSource(DataSource dataSource) {
this.simpleJdbcTemplate = new SimpleJdbcTemplate(dataSource);
}
@Autowired
public void setTransactionManager(PlatformTransactionManager transactionManager) {
this.transactionManager = transactionManager;
}
@Test
public void testLaunchJob() throws Exception {
validatePreConditions();
JobParameters params = new JobParametersBuilder().addString("key", "failureJob").toJobParameters();
setJobParameters(params);
writer.setFailOnFlush(2);
try {
super.testLaunchJob();
jobRunnerUtils.launchJob(params);
} catch (HibernateJdbcException e) {
// This is what would happen if the flush happened outside the
// RepeatContext:
@@ -59,24 +101,73 @@ public class HibernateFailureJobFunctionalTests extends AbstractCustomerCreditIn
}
int after = simpleJdbcTemplate.queryForInt("SELECT COUNT(*) from CUSTOMER");
assertEquals(4, after);
validatePostConditions();
}
/**
* All customers have the same credit
*/
@SuppressWarnings("unchecked")
protected void validatePreConditions() throws Exception {
ensureState();
creditsBeforeUpdate = (List<BigDecimal>) new TransactionTemplate(transactionManager).execute(new TransactionCallback() {
public Object doInTransaction(TransactionStatus status) {
return simpleJdbcTemplate.query(ALL_CUSTOMERS, new ParameterizedRowMapper<BigDecimal>() {
public BigDecimal mapRow(ResultSet rs, int rowNum) throws SQLException {
return rs.getBigDecimal(CREDIT_COLUMN);
}
});
}
});
}
/*
* (non-Javadoc)
*
* @see org.springframework.batch.sample.AbstractCustomerCreditIncreaseTests#checkMatches(java.util.List)
* Ensure the state of the database is accurate by delete all the contents of the
* customer table and reading the expected defaults.
*/
protected void checkMatches(List<BigDecimal> matches) {
assertFalse(matches.contains(new BigDecimal(2)));
}
private void ensureState(){
new TransactionTemplate(transactionManager).execute(new TransactionCallback(){
/*
* (non-Javadoc)
*
* @see org.springframework.batch.sample.AbstractCustomerCreditIncreaseTests#getExpectedMatches()
public Object doInTransaction(TransactionStatus status) {
simpleJdbcTemplate.update(DELETE_CUSTOMERS);
for (String customer : customers) {
simpleJdbcTemplate.update(customer);
}
return null;
}
});
}
/**
* Credit was increased by CREDIT_INCREASE
*/
protected int getExpectedMatches() {
// One record was skipped, so it won't be processed in the final state.
return super.getExpectedMatches() - 1;
protected void validatePostConditions() throws Exception {
final List<BigDecimal> matches = new ArrayList<BigDecimal>();
new TransactionTemplate(transactionManager).execute(new TransactionCallback() {
public Object doInTransaction(TransactionStatus status) {
simpleJdbcTemplate.getJdbcOperations().query(ALL_CUSTOMERS, new RowCallbackHandler() {
private int i = 0;
public void processRow(ResultSet rs) throws SQLException {
final BigDecimal creditBeforeUpdate = creditsBeforeUpdate.get(i++);
final BigDecimal expectedCredit = creditBeforeUpdate.add(CREDIT_INCREASE);
if (expectedCredit.equals(rs.getBigDecimal(CREDIT_COLUMN))) {
matches.add(rs.getBigDecimal(ID_COLUMN));
}
}
});
return null;
}
});
assertEquals((creditsBeforeUpdate.size() - 1), matches.size());
assertFalse(matches.contains(new BigDecimal(2)));
}
}

View File

@@ -24,7 +24,7 @@ import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration
@ContextConfiguration(locations = { "/simple-job-launcher-context.xml", "/jobs/infiniteLoopJob.xml" })
public class JobOperatorFunctionalTests {
private static final Log logger = LogFactory.getLog(JobOperatorFunctionalTests.class);
@@ -40,8 +40,9 @@ public class JobOperatorFunctionalTests {
@Before
public void setUp() throws Exception {
if (!jobRegistry.getJobNames().contains(job.getName()))
if (!jobRegistry.getJobNames().contains(job.getName())) {
jobRegistry.register(new ReferenceJobFactory(job));
}
}
@Test
@@ -78,8 +79,10 @@ public class JobOperatorFunctionalTests {
Thread.sleep(1000);
Set<Long> runningExecutions = operator.getRunningExecutions(job.getName());
assertTrue("Wrong executions: "+runningExecutions+" expected: "+executionId, runningExecutions.contains(executionId));
assertTrue("Wrong summary: "+operator.getSummary(executionId), operator.getSummary(executionId).contains(BatchStatus.STARTED.toString()));
assertTrue("Wrong executions: " + runningExecutions + " expected: " + executionId, runningExecutions
.contains(executionId));
assertTrue("Wrong summary: " + operator.getSummary(executionId), operator.getSummary(executionId).contains(
BatchStatus.STARTED.toString()));
operator.stop(executionId);
@@ -91,8 +94,10 @@ public class JobOperatorFunctionalTests {
}
runningExecutions = operator.getRunningExecutions(job.getName());
assertFalse("Wrong executions: "+runningExecutions+" expected: "+executionId, runningExecutions.contains(executionId));
assertTrue("Wrong summary: "+operator.getSummary(executionId), operator.getSummary(executionId).contains(BatchStatus.STOPPED.toString()));
assertFalse("Wrong executions: " + runningExecutions + " expected: " + executionId, runningExecutions
.contains(executionId));
assertTrue("Wrong summary: " + operator.getSummary(executionId), operator.getSummary(executionId).contains(
BatchStatus.STOPPED.toString()));
// there is just a single step in the test job
Map<Long, String> summaries = operator.getStepExecutionSummaries(executionId);
@@ -113,17 +118,19 @@ public class JobOperatorFunctionalTests {
assertTrue(exec1 != exec2);
assertTrue(operator.getParameters(exec1) != operator.getParameters(exec2));
Set<Long> executions = operator.getRunningExecutions(jobName);
assertTrue(executions.contains(exec1));
assertTrue(executions.contains(exec2));
int count = 0;
boolean running = operator.getSummary(exec1).contains("STARTED") && operator.getSummary(exec2).contains("STARTED");
while (count++<10 && !running) {
boolean running = operator.getSummary(exec1).contains("STARTED")
&& operator.getSummary(exec2).contains("STARTED");
while (count++ < 10 && !running) {
Thread.sleep(100L);
running = operator.getSummary(exec1).contains("STARTED") && operator.getSummary(exec2).contains("STARTED");
running = operator.getSummary(exec1).contains("STARTED") && operator.getSummary(exec2).contains("STARTED");
}
assertTrue(String.format("Jobs not started: [%s] and [%s]",operator.getSummary(exec1),operator.getSummary(exec1)), running);
assertTrue(String.format("Jobs not started: [%s] and [%s]", operator.getSummary(exec1), operator
.getSummary(exec1)), running);
operator.stop(exec1);
operator.stop(exec2);

View File

@@ -20,14 +20,12 @@ import static org.junit.Assert.assertEquals;
import javax.sql.DataSource;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.batch.core.Job;
import org.springframework.batch.core.converter.DefaultJobParametersConverter;
import org.springframework.batch.support.PropertiesConverter;
import org.springframework.batch.test.JobRunnerTestUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.jdbc.core.simple.SimpleJdbcTemplate;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
@@ -38,34 +36,32 @@ import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
* @author Dave Syer
*/
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration()
public class JobStepFunctionalTests extends AbstractBatchLauncherTests {
@ContextConfiguration
public class JobStepFunctionalTests {
@Autowired
private JobRunnerTestUtils jobRunnerUtils;
// auto-injected attributes
private SimpleJdbcTemplate simpleJdbcTemplate;
@Autowired
public void setJob(@Qualifier("jobStepJob") Job job) {
super.setJob(job);
}
@Autowired
public void setDataSource(DataSource dataSource) {
this.simpleJdbcTemplate = new SimpleJdbcTemplate(dataSource);
}
@Before
public void onTearDown() throws Exception {
@Test
public void testJobLaunch() throws Exception {
simpleJdbcTemplate.update("DELETE FROM TRADE");
setJobParameters(new DefaultJobParametersConverter()
jobRunnerUtils.launchJob(new DefaultJobParametersConverter()
.getJobParameters(PropertiesConverter
.stringToProperties("run.id(long)=1,parameter=true,run.date=20070122,input.file=classpath:data/fixedLengthImportJob/input/20070122.teststream.ImportTradeDataStep.txt")));
}
@After
public void onSetUp() {
int after = simpleJdbcTemplate.queryForInt("SELECT COUNT(*) FROM TRADE");
assertEquals(5, after);
}
}

View File

@@ -17,8 +17,10 @@ package org.springframework.batch.sample;
import static org.junit.Assert.assertEquals;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.batch.sample.domain.trade.internal.ItemTrackingTradeItemWriter;
import org.springframework.batch.test.JobRunnerTestUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
@@ -30,13 +32,19 @@ import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
* @since 2.0
*/
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = { "/simple-job-launcher-context.xml", "/jobs/loopFlowSample.xml" })
public class LoopFlowSampleFunctionalTests extends AbstractValidatingBatchLauncherTests {
@ContextConfiguration(locations = { "/simple-job-launcher-context.xml", "/jobs/loopFlowSample.xml",
"/job-runner-context.xml" })
public class LoopFlowSampleFunctionalTests {
@Autowired
private ItemTrackingTradeItemWriter itemWriter;
protected void validatePostConditions() throws Exception {
@Autowired
private JobRunnerTestUtils jobRunnerUtils;
@Test
public void testJobLaunch() throws Exception {
jobRunnerUtils.launchJob();
// items processed = items read + 2 exceptions
assertEquals(10, itemWriter.getItems().size());
}

View File

@@ -19,7 +19,10 @@ package org.springframework.batch.sample;
import static org.junit.Assert.assertEquals;
import org.apache.commons.io.IOUtils;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.batch.test.JobRunnerTestUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.FileSystemResource;
import org.springframework.core.io.Resource;
import org.springframework.test.context.ContextConfiguration;
@@ -27,9 +30,13 @@ import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.util.StringUtils;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration()
public class MultilineJobFunctionalTests extends AbstractValidatingBatchLauncherTests {
@ContextConfiguration(locations = { "/simple-job-launcher-context.xml", "/jobs/multilineJob.xml",
"/job-runner-context.xml" })
public class MultilineJobFunctionalTests {
@Autowired
private JobRunnerTestUtils jobRunnerUtils;
// The output is grouped together in two lines, instead of all the
// trades coming out on a single line.
private static final String EXPECTED_RESULT = "[Trade: [isin=UK21341EAH45,quantity=978,price=98.34,customer=customer1], Trade: [isin=UK21341EAH46,quantity=112,price=18.12,customer=customer2]]"
@@ -37,7 +44,9 @@ public class MultilineJobFunctionalTests extends AbstractValidatingBatchLauncher
private Resource output = new FileSystemResource("target/test-outputs/20070122.testStream.multilineStep.txt");
protected void validatePostConditions() throws Exception {
@Test
public void testJobLaunch() throws Exception {
jobRunnerUtils.launchJob();
assertEquals(EXPECTED_RESULT, StringUtils.replace(IOUtils.toString(output.getInputStream()), System
.getProperty("line.separator"), ""));
}

View File

@@ -20,22 +20,27 @@ import static org.springframework.batch.test.AssertFile.assertFileEquals;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.batch.test.AbstractJobTests;
import org.springframework.batch.test.JobRunnerTestUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.FileSystemResource;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration()
public class MultilineOrderJobFunctionalTests extends AbstractJobTests {
@ContextConfiguration(locations = { "/simple-job-launcher-context.xml", "/jobs/multilineOrderJob.xml",
"/job-runner-context.xml" })
public class MultilineOrderJobFunctionalTests {
private static final String ACTUAL = "target/test-outputs/multilineOrderOutput.txt";
private static final String EXPECTED = "data/multilineOrderJob/result/multilineOrderOutput.txt";
@Autowired
private JobRunnerTestUtils jobRunnerUtils;
@Test
public void testJob() throws Exception {
this.launchJob();
public void testJobLaunch() throws Exception {
jobRunnerUtils.launchJob();
assertFileEquals(new ClassPathResource(EXPECTED), new FileSystemResource(ACTUAL));
}

View File

@@ -33,20 +33,33 @@ import org.springframework.batch.item.ItemReader;
import org.springframework.batch.item.ItemStream;
import org.springframework.batch.sample.domain.trade.CustomerCredit;
import org.springframework.batch.sample.domain.trade.internal.CustomerCreditIncreaseProcessor;
import org.springframework.batch.test.AbstractJobTests;
import org.springframework.batch.test.JobRunnerTestUtils;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration()
public class PartitionFileJobFunctionalTests extends AbstractJobTests {
@ContextConfiguration(locations = { "/simple-job-launcher-context.xml", "/jobs/partitionFileJob.xml",
"/job-runner-context.xml" })
public class PartitionFileJobFunctionalTests implements ApplicationContextAware {
@Autowired
@Qualifier("inputTestReader")
private ItemReader<CustomerCredit> inputReader;
@Autowired
private JobRunnerTestUtils jobRunnerUtils;
private ApplicationContext applicationContext;
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
this.applicationContext = applicationContext;
}
/**
* Check the resulting credits correspond to inputs increased by fixed
* amount.
@@ -54,18 +67,19 @@ public class PartitionFileJobFunctionalTests extends AbstractJobTests {
@Test
public void testUpdateCredit() throws Exception {
assertTrue("Define a prototype bean called 'outputTestReader' to check the output", getApplicationContext()
assertTrue("Define a prototype bean called 'outputTestReader' to check the output", applicationContext
.containsBeanDefinition("outputTestReader"));
open(inputReader);
List<CustomerCredit> inputs = new ArrayList<CustomerCredit>(getCredits(inputReader));
close(inputReader);
JobExecution jobExecution = this.launchJob();
JobExecution jobExecution = jobRunnerUtils.launchJob();
assertEquals(BatchStatus.COMPLETED, jobExecution.getStatus());
@SuppressWarnings("unchecked")
ItemReader<CustomerCredit> outputReader = (ItemReader<CustomerCredit>) getApplicationContext().getBean("outputTestReader");
ItemReader<CustomerCredit> outputReader = (ItemReader<CustomerCredit>) applicationContext
.getBean("outputTestReader");
open(outputReader);
List<CustomerCredit> outputs = new ArrayList<CustomerCredit>(getCredits(outputReader));
close(outputReader);
@@ -112,5 +126,5 @@ public class PartitionFileJobFunctionalTests extends AbstractJobTests {
((ItemStream) reader).close();
}
}
}

View File

@@ -33,20 +33,33 @@ import org.springframework.batch.item.ItemReader;
import org.springframework.batch.item.ItemStream;
import org.springframework.batch.sample.domain.trade.CustomerCredit;
import org.springframework.batch.sample.domain.trade.internal.CustomerCreditIncreaseProcessor;
import org.springframework.batch.test.AbstractJobTests;
import org.springframework.batch.test.JobRunnerTestUtils;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration()
public class PartitionJdbcJobFunctionalTests extends AbstractJobTests {
@ContextConfiguration(locations = { "/simple-job-launcher-context.xml", "/jobs/partitionFileJob.xml",
"/job-runner-context.xml" })
public class PartitionJdbcJobFunctionalTests implements ApplicationContextAware {
@Autowired
@Qualifier("inputTestReader")
private ItemReader<CustomerCredit> inputReader;
@Autowired
private JobRunnerTestUtils jobRunnerUtils;
private ApplicationContext applicationContext;
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
this.applicationContext = applicationContext;
}
/**
* Check the resulting credits correspond to inputs increased by fixed
* amount.
@@ -54,18 +67,19 @@ public class PartitionJdbcJobFunctionalTests extends AbstractJobTests {
@Test
public void testUpdateCredit() throws Exception {
assertTrue("Define a prototype bean called 'outputTestReader' to check the output", getApplicationContext()
assertTrue("Define a prototype bean called 'outputTestReader' to check the output", applicationContext
.containsBeanDefinition("outputTestReader"));
open(inputReader);
List<CustomerCredit> inputs = new ArrayList<CustomerCredit>(getCredits(inputReader));
close(inputReader);
JobExecution jobExecution = this.launchJob();
JobExecution jobExecution = jobRunnerUtils.launchJob();
assertEquals(BatchStatus.COMPLETED, jobExecution.getStatus());
@SuppressWarnings("unchecked")
ItemReader<CustomerCredit> outputReader = (ItemReader<CustomerCredit>) getApplicationContext().getBean("outputTestReader");
ItemReader<CustomerCredit> outputReader = (ItemReader<CustomerCredit>) applicationContext
.getBean("outputTestReader");
open(outputReader);
List<CustomerCredit> outputs = new ArrayList<CustomerCredit>(getCredits(outputReader));
close(outputReader);

View File

@@ -27,8 +27,8 @@ import org.springframework.batch.core.JobExecution;
import org.springframework.batch.core.JobParameters;
import org.springframework.batch.item.file.FlatFileItemWriter;
import org.springframework.batch.sample.domain.trade.CustomerCredit;
import org.springframework.batch.test.AbstractJobTests;
import org.springframework.batch.test.AssertFile;
import org.springframework.batch.test.JobRunnerTestUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.Resource;
import org.springframework.test.context.ContextConfiguration;
@@ -39,21 +39,25 @@ import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
* @since 2.0
*/
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = { "/simple-job-launcher-context.xml", "/jobs/restartFileSampleJob.xml" })
public class RestartFileSampleFunctionalTests extends AbstractJobTests {
@ContextConfiguration(locations = { "/simple-job-launcher-context.xml", "/jobs/restartFileSampleJob.xml",
"/job-runner-context.xml" })
public class RestartFileSampleFunctionalTests {
@Autowired
private Resource outputResource;
@Autowired
private JobRunnerTestUtils jobRunnerUtils;
@Test
public void runTest() throws Exception {
JobParameters jobParameters = getUniqueJobParameters();
JobParameters jobParameters = jobRunnerUtils.getUniqueJobParameters();
JobExecution je1 = this.launchJob(jobParameters);
JobExecution je1 = jobRunnerUtils.launchJob(jobParameters);
assertEquals(BatchStatus.FAILED, je1.getStatus());
AssertFile.assertLineCount(10, outputResource);
JobExecution je2 = this.launchJob(jobParameters);
JobExecution je2 = jobRunnerUtils.launchJob(jobParameters);
assertEquals(BatchStatus.COMPLETED, je2.getStatus());
AssertFile.assertLineCount(20, outputResource);
}

View File

@@ -26,6 +26,7 @@ import org.springframework.batch.core.BatchStatus;
import org.springframework.batch.core.JobExecution;
import org.springframework.batch.core.converter.DefaultJobParametersConverter;
import org.springframework.batch.support.PropertiesConverter;
import org.springframework.batch.test.JobRunnerTestUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.simple.SimpleJdbcTemplate;
import org.springframework.test.context.ContextConfiguration;
@@ -39,8 +40,12 @@ import org.springframework.test.context.transaction.BeforeTransaction;
* @author Dave Syer
*/
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration()
public class RestartFunctionalTests extends AbstractBatchLauncherTests {
@ContextConfiguration(locations = { "/simple-job-launcher-context.xml", "/jobs/restartSample.xml",
"/job-runner-context.xml" })
public class RestartFunctionalTests {
@Autowired
private JobRunnerTestUtils jobRunnerUtils;
// auto-injected attributes
private SimpleJdbcTemplate simpleJdbcTemplate;
@@ -94,12 +99,10 @@ public class RestartFunctionalTests extends AbstractBatchLauncherTests {
// load the application context and launch the job
private JobExecution runJobForRestartTest() throws Exception {
return getLauncher()
.run(
getJob(),
new DefaultJobParametersConverter()
.getJobParameters(PropertiesConverter
.stringToProperties("run.id(long)=1,parameter=true,run.date=20070122,input.file=classpath:data/fixedLengthImportJob/input/20070122.teststream.ImportTradeDataStep.txt")));
return jobRunnerUtils
.launchJob(new DefaultJobParametersConverter()
.getJobParameters(PropertiesConverter
.stringToProperties("run.id(long)=1,parameter=true,run.date=20070122,input.file=classpath:data/fixedLengthImportJob/input/20070122.teststream.ImportTradeDataStep.txt")));
}
}

View File

@@ -2,9 +2,11 @@ package org.springframework.batch.sample;
import static org.junit.Assert.assertEquals;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.batch.sample.domain.trade.internal.GeneratingTradeItemReader;
import org.springframework.batch.sample.support.RetrySampleItemWriter;
import org.springframework.batch.test.JobRunnerTestUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
@@ -15,8 +17,9 @@ import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
* @author Robert Kasanicky
*/
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration()
public class RetrySampleFunctionalTests extends AbstractValidatingBatchLauncherTests {
@ContextConfiguration(locations = { "/simple-job-launcher-context.xml", "/jobs/retrySample.xml",
"/job-runner-context.xml" })
public class RetrySampleFunctionalTests {
@Autowired
private GeneratingTradeItemReader itemGenerator;
@@ -24,7 +27,12 @@ public class RetrySampleFunctionalTests extends AbstractValidatingBatchLauncherT
@Autowired
private RetrySampleItemWriter<?> itemProcessor;
protected void validatePostConditions() throws Exception {
@Autowired
private JobRunnerTestUtils jobRunnerUtils;
@Test
public void testLaunchJob() throws Exception {
jobRunnerUtils.launchJob();
//items processed = items read + 2 exceptions
assertEquals(itemGenerator.getLimit()+2, itemProcessor.getCounter());
}

View File

@@ -23,22 +23,23 @@ import org.junit.runner.RunWith;
import org.springframework.batch.core.BatchStatus;
import org.springframework.batch.core.JobExecution;
import org.springframework.batch.core.JobParametersBuilder;
import org.springframework.batch.test.JobRunnerTestUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration()
public class TaskletJobFunctionalTests extends AbstractValidatingBatchLauncherTests {
@ContextConfiguration(locations = { "/simple-job-launcher-context.xml", "/jobs/taskletJob.xml",
"/job-runner-context.xml" })
public class TaskletJobFunctionalTests {
@Autowired
private JobRunnerTestUtils jobRunnerUtils;
@Test
public void testLaunchJob() throws Exception {
setJobParameters(new JobParametersBuilder().addString("value", "foo").toJobParameters());
super.testLaunchJob();
}
@Override
protected void validatePostConditions() throws Exception {
JobExecution jobExecution = getJobExecution();
JobExecution jobExecution = jobRunnerUtils.launchJob(new JobParametersBuilder().addString("value", "foo")
.toJobParameters());
assertEquals(BatchStatus.COMPLETED, jobExecution.getStatus());
}

View File

@@ -31,8 +31,10 @@ import javax.sql.DataSource;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.batch.sample.domain.trade.Trade;
import org.springframework.batch.test.JobRunnerTestUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.RowCallbackHandler;
import org.springframework.jdbc.core.simple.SimpleJdbcTemplate;
@@ -40,8 +42,9 @@ import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration()
public class TradeJobFunctionalTests extends AbstractValidatingBatchLauncherTests {
@ContextConfiguration(locations = { "/simple-job-launcher-context.xml", "/jobs/tradeJob.xml",
"/job-runner-context.xml" })
public class TradeJobFunctionalTests {
private static final String GET_TRADES = "select ISIN, QUANTITY, PRICE, CUSTOMER, ID, VERSION from TRADE order by ISIN";
private static final String GET_CUSTOMERS = "select NAME, CREDIT from CUSTOMER order by NAME";
@@ -53,6 +56,9 @@ public class TradeJobFunctionalTests extends AbstractValidatingBatchLauncherTest
private SimpleJdbcTemplate simpleJdbcTemplate;
private Map<String, Double> credits = new HashMap<String, Double>();
@Autowired
private JobRunnerTestUtils jobRunnerUtils;
@Autowired
public void setDataSource(DataSource dataSource) {
this.simpleJdbcTemplate = new SimpleJdbcTemplate(dataSource);
@@ -61,7 +67,7 @@ public class TradeJobFunctionalTests extends AbstractValidatingBatchLauncherTest
@Before
public void onSetUp() throws Exception {
simpleJdbcTemplate.update("delete from TRADE");
List<Map<String, Object>> list = simpleJdbcTemplate.queryForList("select name, CREDIT from CUSTOMER");
List<Map<String, Object>> list = simpleJdbcTemplate.queryForList("select NAME, CREDIT from CUSTOMER");
for (Map<String, Object> map : list) {
credits.put((String) map.get("NAME"), ((Number) map.get("CREDIT")).doubleValue());
}
@@ -72,7 +78,10 @@ public class TradeJobFunctionalTests extends AbstractValidatingBatchLauncherTest
simpleJdbcTemplate.update("delete from TRADE");
}
protected void validatePostConditions() {
@Test
public void testLaunchJob() throws Exception {
jobRunnerUtils.launchJob();
customers = Arrays.asList(new Customer("customer1", (credits.get("customer1") - 98.34)),
new Customer("customer2", (credits.get("customer2") - 18.12 - 12.78)),
@@ -98,7 +107,7 @@ public class TradeJobFunctionalTests extends AbstractValidatingBatchLauncherTest
}
});
assertTrue(trades.size() == activeRow);
assertEquals(activeRow, trades.size());
// check content of the customer table
activeRow = 0;
@@ -126,33 +135,19 @@ public class TradeJobFunctionalTests extends AbstractValidatingBatchLauncherTest
this.credit = credit;
}
public Customer(){
}
/**
* @return the credit
*/
public double getCredit() {
return credit;
}
/**
* @param credit the credit to set
*/
public void setCredit(double credit) {
this.credit = credit;
}
/**
* @return the name
*/
public String getName() {
return name;
}
/**
* @param name the name to set
*/
public void setName(String name) {
this.name = name;
}
@Override
public int hashCode() {

View File

@@ -1,20 +1,23 @@
package org.springframework.batch.sample.iosample;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import java.util.ArrayList;
import java.util.List;
import static org.junit.Assert.*;
import org.junit.Test;
import org.springframework.batch.core.BatchStatus;
import org.springframework.batch.core.JobExecution;
import org.springframework.batch.core.JobParameters;
import org.springframework.batch.item.ExecutionContext;
import org.springframework.batch.item.ItemReader;
import org.springframework.batch.item.ItemStream;
import org.springframework.batch.sample.domain.trade.CustomerCredit;
import org.springframework.batch.sample.domain.trade.internal.CustomerCreditIncreaseProcessor;
import org.springframework.batch.test.AbstractJobTests;
import org.springframework.batch.test.JobRunnerTestUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
/**
* Base class for IoSample tests that increase input customer credit by fixed
@@ -23,7 +26,11 @@ import org.springframework.beans.factory.annotation.Autowired;
*
* @author Robert Kasanicky
*/
public abstract class AbstractIoSampleTests extends AbstractJobTests {
@ContextConfiguration(locations = { "/simple-job-launcher-context.xml", "/job-runner-context.xml", "/jobs/ioSampleJob.xml" })
public abstract class AbstractIoSampleTests {
@Autowired
private JobRunnerTestUtils jobRunnerUtils;
@Autowired
private ItemReader<CustomerCredit> reader;
@@ -39,7 +46,7 @@ public abstract class AbstractIoSampleTests extends AbstractJobTests {
List<CustomerCredit> inputs = getCredits(reader);
close(reader);
JobExecution jobExecution = this.launchJob();
JobExecution jobExecution = jobRunnerUtils.launchJob(getUniqueJobParameters());
assertEquals(BatchStatus.COMPLETED, jobExecution.getStatus());
pointReaderToOutput(reader);
@@ -50,7 +57,7 @@ public abstract class AbstractIoSampleTests extends AbstractJobTests {
assertEquals(inputs.size(), outputs.size());
int itemCount = inputs.size();
assertTrue(itemCount > 0);
for (int i = 0; i < itemCount; i++) {
assertEquals(inputs.get(i).getCredit().add(CustomerCreditIncreaseProcessor.FIXED_AMOUNT).intValue(),
outputs.get(i).getCredit().intValue());
@@ -58,6 +65,10 @@ public abstract class AbstractIoSampleTests extends AbstractJobTests {
}
protected JobParameters getUniqueJobParameters() {
return jobRunnerUtils.getUniqueJobParameters();
}
/**
* Configure the reader to read outputs (if necessary). Required for
* file-to-file jobs jobs, usually no-op for database jobs where inputs are

View File

@@ -32,8 +32,7 @@ import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
* @since 2.0
*/
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = { "/simple-job-launcher-context.xml", "/jobs/ioSampleJob.xml",
"/jobs/iosample/delimited.xml" })
@ContextConfiguration(locations = "/jobs/iosample/delimited.xml")
public class DelimitedFunctionalTests extends AbstractIoSampleTests {
@Autowired

View File

@@ -26,8 +26,7 @@ import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = { "/simple-job-launcher-context.xml", "/jobs/ioSampleJob.xml",
"/jobs/iosample/fixedLength.xml" })
@ContextConfiguration(locations = "/jobs/iosample/fixedLength.xml")
public class FixedLengthFunctionalTests extends AbstractIoSampleTests {
@Autowired

View File

@@ -7,8 +7,7 @@ import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = { "/simple-job-launcher-context.xml", "/hibernate-context.xml",
"/jobs/ioSampleJob.xml", "/jobs/iosample/hibernate.xml" })
@ContextConfiguration(locations = { "/hibernate-context.xml", "/jobs/iosample/hibernate.xml" })
public class HibernateFunctionalTests extends AbstractIoSampleTests {
@Override

View File

@@ -7,8 +7,7 @@ import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = { "/simple-job-launcher-context.xml", "/jobs/ioSampleJob.xml",
"/jobs/iosample/ibatis.xml" })
@ContextConfiguration(locations = "/jobs/iosample/ibatis.xml")
public class IbatisFunctionalTests extends AbstractIoSampleTests {
@Override

View File

@@ -27,8 +27,7 @@ import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
* @since 2.0
*/
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = { "/simple-job-launcher-context.xml", "/jobs/ioSampleJob.xml",
"/jobs/iosample/jdbcCursor.xml" })
@ContextConfiguration(locations = "/jobs/iosample/jdbcCursor.xml")
public class JdbcCursorFunctionalTests extends AbstractIoSampleTests {
@Override

View File

@@ -29,8 +29,7 @@ import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
* @since 2.0
*/
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = { "/simple-job-launcher-context.xml", "/jobs/ioSampleJob.xml",
"/jobs/iosample/jdbcPaging.xml" })
@ContextConfiguration(locations = "/jobs/iosample/jdbcPaging.xml")
public class JdbcPagingFunctionalTests extends AbstractIoSampleTests {
@Override

View File

@@ -7,8 +7,7 @@ import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = { "/simple-job-launcher-context.xml", "/jobs/ioSampleJob.xml",
"/jobs/iosample/jpa.xml" })
@ContextConfiguration(locations = "/jobs/iosample/jpa.xml")
public class JpaFunctionalTests extends AbstractIoSampleTests {
@Override

View File

@@ -18,8 +18,9 @@ package org.springframework.batch.sample.iosample;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.batch.test.AbstractJobTests;
import org.springframework.batch.test.AssertFile;
import org.springframework.batch.test.JobRunnerTestUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.FileSystemResource;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
@@ -29,19 +30,23 @@ import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
* @since 2.0
*/
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = { "/simple-job-launcher-context.xml", "/jobs/iosample/multiLine.xml" })
public class MultiLineFunctionalTests extends AbstractJobTests {
@ContextConfiguration(locations = { "/simple-job-launcher-context.xml", "/jobs/iosample/multiLine.xml",
"/job-runner-context.xml" })
public class MultiLineFunctionalTests {
private static final String OUTPUT_FILE = "target/test-outputs/multiLineOutput.txt";
private static final String INPUT_FILE = "src/main/resources/data/iosample/input/multiLine.txt";
@Autowired
private JobRunnerTestUtils jobRunnerUtils;
/**
* Output should be the same as input
*/
@Test
public void testJob() throws Exception {
this.launchJob();
jobRunnerUtils.launchJob();
AssertFile.assertFileEquals(new FileSystemResource(INPUT_FILE), new FileSystemResource(OUTPUT_FILE));
}
}

View File

@@ -18,8 +18,9 @@ package org.springframework.batch.sample.iosample;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.batch.test.AbstractJobTests;
import org.springframework.batch.test.AssertFile;
import org.springframework.batch.test.JobRunnerTestUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.FileSystemResource;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
@@ -29,19 +30,23 @@ import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
* @since 2.0
*/
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = { "/simple-job-launcher-context.xml", "/jobs/iosample/multiRecordType.xml" })
public class MultiRecordTypeFunctionalTests extends AbstractJobTests {
@ContextConfiguration(locations = { "/simple-job-launcher-context.xml", "/jobs/iosample/multiRecordType.xml",
"/job-runner-context.xml" })
public class MultiRecordTypeFunctionalTests {
private static final String OUTPUT_FILE = "target/test-outputs/multiRecordTypeOutput.txt";
private static final String INPUT_FILE = "src/main/resources/data/iosample/input/multiRecordType.txt";
@Autowired
private JobRunnerTestUtils jobRunnerUtils;
/**
* Output should be the same as input
*/
@Test
public void testJob() throws Exception {
this.launchJob();
jobRunnerUtils.launchJob();
AssertFile.assertFileEquals(new FileSystemResource(INPUT_FILE), new FileSystemResource(OUTPUT_FILE));
}
}

View File

@@ -32,8 +32,7 @@ import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
* @since 2.0
*/
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = { "/simple-job-launcher-context.xml", "/jobs/ioSampleJob.xml",
"/jobs/iosample/multiResource.xml" })
@ContextConfiguration(locations = "/jobs/iosample/multiResource.xml")
public class MultiResourceFunctionalTests extends AbstractIoSampleTests {
@Override

View File

@@ -30,8 +30,7 @@ import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
* @since 2.0
*/
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = { "/simple-job-launcher-context.xml", "/jobs/ioSampleJob.xml",
"/jobs/iosample/xml.xml" })
@ContextConfiguration(locations = "/jobs/iosample/xml.xml" )
public class XmlFunctionalTests extends AbstractIoSampleTests {
@Autowired

View File

@@ -0,0 +1,10 @@
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.0.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-2.5.xsd">
<context:annotation-config/>
<bean class="org.springframework.batch.test.JobRunnerTestUtils"/>
</beans>

View File

@@ -1,10 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.0.xsd">
<import resource="classpath:/simple-job-launcher-context.xml" />
<import resource="classpath:/jobs/beanWrapperMapperSampleJob.xml" />
</beans>

View File

@@ -1,10 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.0.xsd">
<import resource="classpath:/simple-job-launcher-context.xml" />
<import resource="classpath:/jobs/compositeItemWriterSampleJob.xml" />
</beans>

View File

@@ -1,10 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.0.xsd">
<import resource="classpath:/simple-job-launcher-context.xml" />
<import resource="classpath:/jobs/customerFilterJob.xml" />
</beans>

View File

@@ -1,10 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.0.xsd">
<import resource="classpath:/simple-job-launcher-context.xml" />
<import resource="classpath:/jobs/infiniteLoopJob.xml" />
</beans>

View File

@@ -1,10 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.0.xsd">
<import resource="classpath:/simple-job-launcher-context.xml" />
<import resource="classpath:/jobs/delegatingJob.xml" />
</beans>

View File

@@ -1,10 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.0.xsd">
<import resource="classpath:/simple-job-launcher-context.xml" />
<import resource="classpath:/jobs/footballJob.xml" />
</beans>

View File

@@ -1,10 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.0.xsd">
<import resource="classpath:/simple-job-launcher-context.xml" />
<import resource="classpath:/jobs/infiniteLoopJob.xml" />
</beans>

View File

@@ -1,10 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.0.xsd">
<import resource="classpath:/simple-job-launcher-context.xml" />
<import resource="classpath:/jobs/groovyJob.xml" />
</beans>

View File

@@ -1,10 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.0.xsd">
<import resource="classpath:/simple-job-launcher-context.xml" />
<import resource="classpath:/jobs/headerFooterSample.xml" />
</beans>

View File

@@ -1,11 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.0.xsd">
<import resource="classpath:/simple-job-launcher-context.xml" />
<import resource="classpath:/hibernate-context.xml" />
<import resource="classpath:/jobs/hibernateJob.xml" />
</beans>

View File

@@ -1,14 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.0.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd"
xmlns:tx="http://www.springframework.org/schema/tx">
<import resource="classpath:/simple-job-launcher-context.xml" />
<import resource="classpath:/jobs/infiniteLoopJob.xml" />
<tx:annotation-driven/>
</beans>

View File

@@ -1,10 +1,13 @@
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.0.xsd">
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.0.xsd">
<import resource="classpath:/simple-job-launcher-context.xml" />
<import resource="classpath:/jobs/jobStepSample.xml" />
<bean class="org.springframework.batch.test.JobRunnerTestUtils">
<property name="job" ref="jobStepJob"/>
</bean>
</beans>

View File

@@ -1,10 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.0.xsd">
<import resource="classpath:/simple-job-launcher-context.xml" />
<import resource="classpath:/jobs/multilineJob.xml" />
</beans>

View File

@@ -1,10 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.0.xsd">
<import resource="classpath:/simple-job-launcher-context.xml" />
<import resource="classpath:/jobs/multilineOrderJob.xml" />
</beans>

View File

@@ -1,10 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.0.xsd">
<import resource="classpath:/simple-job-launcher-context.xml" />
<import resource="classpath:/jobs/parallelJob.xml" />
</beans>

View File

@@ -1,10 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.0.xsd">
<import resource="classpath:/simple-job-launcher-context.xml" />
<import resource="classpath:/jobs/partitionFileJob.xml" />
</beans>

View File

@@ -1,10 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.0.xsd">
<import resource="classpath:/simple-job-launcher-context.xml" />
<import resource="classpath:/jobs/partitionJdbcJob.xml" />
</beans>

View File

@@ -1,10 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.0.xsd">
<import resource="classpath:/simple-job-launcher-context.xml" />
<import resource="classpath:/jobs/restartSample.xml" />
</beans>

View File

@@ -1,10 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.0.xsd">
<import resource="classpath:/simple-job-launcher-context.xml" />
<import resource="classpath:/jobs/retrySample.xml" />
</beans>

View File

@@ -1,10 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.0.xsd">
<import resource="classpath:/simple-job-launcher-context.xml" />
<import resource="classpath:/jobs/taskletJob.xml" />
</beans>

View File

@@ -1,10 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.0.xsd">
<import resource="classpath:/simple-job-launcher-context.xml" />
<import resource="classpath:/jobs/tradeJob.xml" />
</beans>

View File

@@ -64,6 +64,8 @@ import org.springframework.context.ApplicationContextAware;
* @author Lucas Ward
* @author Dan Garrette
* @since 2.0
*
* @deprecated (from 2.1) use {@link JobRunnerTestUtils} instead
*/
public abstract class AbstractJobTests implements ApplicationContextAware {

View File

@@ -0,0 +1,234 @@
/*
* Copyright 2006-2007 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.batch.test;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.batch.core.Job;
import org.springframework.batch.core.JobExecution;
import org.springframework.batch.core.JobParameter;
import org.springframework.batch.core.JobParameters;
import org.springframework.batch.core.Step;
import org.springframework.batch.core.job.AbstractJob;
import org.springframework.batch.core.job.SimpleJob;
import org.springframework.batch.core.job.flow.FlowJob;
import org.springframework.batch.core.launch.JobLauncher;
import org.springframework.batch.core.repository.JobRepository;
import org.springframework.batch.item.ExecutionContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
/**
* <p>
* Utility class for testing batch jobs. It provides methods for launching an
* entire {@link AbstractJob}, allowing for end to end testing of individual
* steps, without having to run every step in the job. Any test classes using
* this utility can set up an instance in the {@link ApplicationContext} as part
* of the Spring test framework.
* </p>
*
* <p>
* This class also provides the ability to run {@link Step}s from a
* {@link FlowJob} or {@link SimpleJob} individually. By launching {@link Step}s
* within a {@link Job} on their own, end to end testing of individual steps can
* be performed without having to run every step in the job.
* </p>
*
* <p>
* It should be noted that using any of the methods that don't contain
* {@link JobParameters} in their signature, will result in one being created
* with the current system time as a parameter. This will ensure restartability
* when no parameters are provided.
* </p>
*
* @author Lucas Ward
* @author Dan Garrette
* @author Dave Syer
* @since 2.1
*/
public class JobRunnerTestUtils {
/** Logger */
protected final Log logger = LogFactory.getLog(getClass());
private JobLauncher jobLauncher;
private AbstractJob job;
private JobRepository jobRepository;
private StepRunner stepRunner;
/**
* The Job instance that can be manipulated (e.g. launched) in this utility.
*
* @param job the {@link AbstractJob} to use
*/
@Autowired
public void setJob(AbstractJob job) {
this.job = job;
}
/**
* The {@link JobRepository} to use for creating new {@link JobExecution}
* instances.
*
* @param jobRepository a {@link JobRepository}
*/
@Autowired
public void setJobRepository(JobRepository jobRepository) {
this.jobRepository = jobRepository;
}
/**
* @return the job repository
*/
public JobRepository getJobRepository() {
return jobRepository;
}
/**
* @return the job
*/
public AbstractJob getJob() {
return job;
}
/**
* A {@link JobLauncher} instance that can be used to launch jobs.
*
* @param jobLauncher a job launcher
*/
@Autowired
public void setJobLauncher(JobLauncher jobLauncher) {
this.jobLauncher = jobLauncher;
}
/**
* @return the job launcher
*/
public JobLauncher getJobLauncher() {
return jobLauncher;
}
/**
* Launch the entire job, including all steps.
*
* @return JobExecution, so that the test can validate the exit status
* @throws Exception
*/
public JobExecution launchJob() throws Exception {
return this.launchJob(this.getUniqueJobParameters());
}
/**
* Launch the entire job, including all steps
*
* @param jobParameters
* @return JobExecution, so that the test can validate the exit status
* @throws Exception
*/
public JobExecution launchJob(JobParameters jobParameters) throws Exception {
return getJobLauncher().run(this.job, jobParameters);
}
/**
* @return a new JobParameters object containing only a parameter for the
* current timestamp, to ensure that the job instance will be unique.
*/
public JobParameters getUniqueJobParameters() {
Map<String, JobParameter> parameters = new HashMap<String, JobParameter>();
parameters.put("timestamp", new JobParameter(new Date().getTime()));
return new JobParameters(parameters);
}
/**
* Convenient method for subclasses to grab a {@link StepRunner} for running
* steps by name.
*
* @return a {@link StepRunner}
*/
protected StepRunner getStepRunner() {
if (this.stepRunner == null) {
this.stepRunner = new StepRunner(getJobLauncher(), getJobRepository());
}
return this.stepRunner;
}
/**
* Launch just the specified step in the job. A unique set of JobParameters
* will automatically be generated. An IllegalStateException is thrown if
* there is no Step with the given name.
*
* @param stepName The name of the step to launch
* @return JobExecution
*/
public JobExecution launchStep(String stepName) {
return this.launchStep(stepName, this.getUniqueJobParameters(), null);
}
/**
* Launch just the specified step in the job. A unique set of JobParameters
* will automatically be generated. An IllegalStateException is thrown if
* there is no Step with the given name.
*
* @param stepName The name of the step to launch
* @param jobExecutionContext An ExecutionContext whose values will be
* loaded into the Job ExecutionContext prior to launching the step.
* @return JobExecution
*/
public JobExecution launchStep(String stepName, ExecutionContext jobExecutionContext) {
return this.launchStep(stepName, this.getUniqueJobParameters(), jobExecutionContext);
}
/**
* Launch just the specified step in the job. An IllegalStateException is
* thrown if there is no Step with the given name.
*
* @param stepName The name of the step to launch
* @param jobParameters The JobParameters to use during the launch
* @return JobExecution
*/
public JobExecution launchStep(String stepName, JobParameters jobParameters) {
return this.launchStep(stepName, jobParameters, null);
}
/**
* Launch just the specified step in the job. An IllegalStateException is
* thrown if there is no Step with the given name.
*
* @param stepName The name of the step to launch
* @param jobParameters The JobParameters to use during the launch
* @param jobExecutionContext An ExecutionContext whose values will be
* loaded into the Job ExecutionContext prior to launching the step.
* @return JobExecution
*/
public JobExecution launchStep(String stepName, JobParameters jobParameters, ExecutionContext jobExecutionContext) {
Step step = this.job.getStep(stepName);
if (step == null) {
step = this.job.getStep(this.job.getName() + "." + stepName);
}
if (step == null) {
throw new IllegalStateException("No Step found with name: [" + stepName + "]");
}
return getStepRunner().launchStep(step, jobParameters, jobExecutionContext);
}
}

View File

@@ -12,6 +12,7 @@ import org.springframework.batch.test.sample.SampleTasklet;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.jdbc.core.simple.SimpleJdbcTemplate;
import org.springframework.test.context.ContextConfiguration;
/**
* This is an abstract test class to be used by test classes to test the
@@ -20,10 +21,14 @@ import org.springframework.jdbc.core.simple.SimpleJdbcTemplate;
* @author Dan Garrette
* @since 2.0
*/
public abstract class AbstractSampleJobTests extends AbstractJobTests {
@ContextConfiguration(locations = { "/simple-job-launcher-context.xml", "/job-runner-context.xml" })
public abstract class AbstractSampleJobTests {
private SimpleJdbcTemplate jdbcTemplate;
@Autowired
private JobRunnerTestUtils jobRunnerUtils;
@Autowired
@Qualifier("tasklet2")
private SampleTasklet tasklet2;
@@ -46,25 +51,25 @@ public abstract class AbstractSampleJobTests extends AbstractJobTests {
@Test
public void testJob() throws Exception {
assertEquals(BatchStatus.COMPLETED, this.launchJob().getStatus());
assertEquals(BatchStatus.COMPLETED, jobRunnerUtils.launchJob().getStatus());
this.verifyTasklet(1);
this.verifyTasklet(2);
}
@Test(expected = IllegalStateException.class)
public void testNonExistentStep() {
launchStep("nonExistent");
jobRunnerUtils.launchStep("nonExistent");
}
@Test
public void testStep1Execution() {
assertEquals(BatchStatus.COMPLETED, this.launchStep("step1").getStatus());
assertEquals(BatchStatus.COMPLETED, jobRunnerUtils.launchStep("step1").getStatus());
this.verifyTasklet(1);
}
@Test
public void testStep2Execution() {
assertEquals(BatchStatus.COMPLETED, this.launchStep("step2").getStatus());
assertEquals(BatchStatus.COMPLETED, jobRunnerUtils.launchStep("step2").getStatus());
this.verifyTasklet(2);
}
@@ -72,7 +77,7 @@ public abstract class AbstractSampleJobTests extends AbstractJobTests {
public void testStepLaunchJobContextEntry() {
ExecutionContext jobContext = new ExecutionContext();
jobContext.put("key1", "value1");
assertEquals(BatchStatus.COMPLETED, this.launchStep("step2", jobContext).getStatus());
assertEquals(BatchStatus.COMPLETED, jobRunnerUtils.launchStep("step2", jobContext).getStatus());
this.verifyTasklet(2);
assertTrue(tasklet2.jobContextEntryFound);
}

View File

@@ -7,13 +7,13 @@ import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
/**
* This class will specifically test the capabilities of
* {@link AbstractSampleJobTests} to test {@link FlowJob}s.
* {@link JobRepositoryTestUtils} to test {@link FlowJob}s.
*
* @author Dan Garrette
* @since 2.0
*/
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = { "/simple-job-launcher-context.xml", "/jobs/sampleFlowJob.xml" })
@ContextConfiguration(locations = "/jobs/sampleFlowJob.xml")
public class SampleFlowJobTests extends AbstractSampleJobTests {
}

View File

@@ -7,13 +7,13 @@ import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
/**
* This class will specifically test the capabilities of
* {@link AbstractSampleJobTests} to test {@link SimpleJob}s.
* {@link JobRepositoryTestUtils} to test {@link SimpleJob}s.
*
* @author Dan Garrette
* @since 2.0
*/
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = { "/simple-job-launcher-context.xml", "/jobs/sampleSimpleJob.xml" })
@ContextConfiguration(locations = "/jobs/sampleSimpleJob.xml")
public class SampleSimpleJobTests extends AbstractSampleJobTests {
}

View File

@@ -0,0 +1,10 @@
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.0.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-2.5.xsd">
<context:annotation-config/>
<bean class="org.springframework.batch.test.JobRunnerTestUtils"/>
</beans>