diff --git a/spring-batch-core/src/test/java/org/springframework/batch/core/JobParametersTests.java b/spring-batch-core/src/test/java/org/springframework/batch/core/JobParametersTests.java index 76ae19203..44b3ae3e0 100644 --- a/spring-batch-core/src/test/java/org/springframework/batch/core/JobParametersTests.java +++ b/spring-batch-core/src/test/java/org/springframework/batch/core/JobParametersTests.java @@ -253,7 +253,8 @@ public class JobParametersTests extends TestCase { public void testSerialization() { JobParameters params = getNewParameters(); - byte[] serialized = SerializationUtils.serialize(params); + byte[] serialized = + SerializationUtils.serialize(params); assertEquals(params, SerializationUtils.deserialize(serialized)); } diff --git a/spring-batch-samples/pom.xml b/spring-batch-samples/pom.xml index 6c4ec53de..1be0e667b 100644 --- a/spring-batch-samples/pom.xml +++ b/spring-batch-samples/pom.xml @@ -133,8 +133,9 @@ test - easymock + org.easymock easymock + 2.4 diff --git a/spring-batch-samples/src/main/java/org/springframework/batch/sample/dao/JdbcCustomerDebitDao.java b/spring-batch-samples/src/main/java/org/springframework/batch/sample/dao/JdbcCustomerDebitDao.java index 449f8b355..e6ee65d12 100644 --- a/spring-batch-samples/src/main/java/org/springframework/batch/sample/dao/JdbcCustomerDebitDao.java +++ b/spring-batch-samples/src/main/java/org/springframework/batch/sample/dao/JdbcCustomerDebitDao.java @@ -18,6 +18,11 @@ package org.springframework.batch.sample.dao; import org.springframework.batch.sample.domain.CustomerDebit; import org.springframework.jdbc.core.JdbcOperations; +import org.springframework.jdbc.core.simple.SimpleJdbcOperations; +import org.springframework.jdbc.core.simple.SimpleJdbcTemplate; +import org.springframework.beans.factory.annotation.Autowired; + +import javax.sql.DataSource; /** @@ -29,15 +34,15 @@ public class JdbcCustomerDebitDao implements CustomerDebitDao { private static final String UPDATE_CREDIT = "UPDATE customer SET credit= credit-? WHERE name=?"; - private JdbcOperations jdbcTemplate; + private SimpleJdbcOperations simpleJdbcTemplate; public void write(CustomerDebit customerDebit) { - jdbcTemplate.update(UPDATE_CREDIT, - new Object[] { customerDebit.getDebit(), customerDebit.getName() }); + simpleJdbcTemplate.update(UPDATE_CREDIT, customerDebit.getDebit(), customerDebit.getName()); } - public void setJdbcTemplate(JdbcOperations jdbcTemplate) { - this.jdbcTemplate = jdbcTemplate; + @Autowired + public void setDataSource(DataSource dataSource) { + this.simpleJdbcTemplate = new SimpleJdbcTemplate(dataSource); } } diff --git a/spring-batch-samples/src/main/java/org/springframework/batch/sample/dao/JdbcGameDao.java b/spring-batch-samples/src/main/java/org/springframework/batch/sample/dao/JdbcGameDao.java index b0f9d05be..950628733 100644 --- a/spring-batch-samples/src/main/java/org/springframework/batch/sample/dao/JdbcGameDao.java +++ b/spring-batch-samples/src/main/java/org/springframework/batch/sample/dao/JdbcGameDao.java @@ -4,31 +4,45 @@ import org.springframework.batch.item.ClearFailedException; import org.springframework.batch.item.FlushFailedException; import org.springframework.batch.item.ItemWriter; import org.springframework.batch.sample.domain.Game; -import org.springframework.jdbc.core.support.JdbcDaoSupport; +import org.springframework.jdbc.core.namedparam.MapSqlParameterSource; +import org.springframework.jdbc.core.namedparam.SqlParameterSource; +import org.springframework.jdbc.core.simple.SimpleJdbcDaoSupport; +import org.springframework.jdbc.core.simple.SimpleJdbcInsert; -public class JdbcGameDao extends JdbcDaoSupport implements ItemWriter { +public class JdbcGameDao extends SimpleJdbcDaoSupport implements ItemWriter { - private static final String INSERT_GAME = "INSERT into GAMES(player_id,year_no,team,week,opponent," - + "completes,attempts,passing_yards,passing_td,interceptions,rushes,rush_yards," - + "receptions,receptions_yards,total_td) values(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)"; + private SimpleJdbcInsert insertGame; + + + protected void initDao() throws Exception { + super.initDao(); + insertGame = new SimpleJdbcInsert(getDataSource()) + .withTableName("GAMES") + .usingColumns("player_id", "year_no", "team", "week", "opponent", " completes", "attempts", + "passing_yards", "passing_td", "interceptions", "rushes", "rush_yards", "receptions", + "receptions_yards", "total_td"); + } public void write(Game game) { + + SqlParameterSource values = new MapSqlParameterSource() + .addValue("player_id", game.getId()) + .addValue("year_no", game.getYear()) + .addValue("team", game.getTeam()) + .addValue("week", game.getWeek()) + .addValue("opponent", game.getOpponent()) + .addValue("completes", game.getCompletes()) + .addValue("attempts", game.getAttempts()) + .addValue("passing_yards", game.getPassingYards()) + .addValue("passing_td", game.getPassingTd()) + .addValue("interceptions", game.getInterceptions()) + .addValue("rushes", game.getRushes()) + .addValue("rush_yards", game.getRushYards()) + .addValue("receptions", game.getReceptions()) + .addValue("receptions_yards", game.getReceptionYards()) + .addValue("total_td", game.getTotalTd()); + this.insertGame.execute(values); - Object[] args = new Object[] { game.getId(), - new Integer(game.getYear()), game.getTeam(), - new Integer(game.getWeek()), game.getOpponent(), - new Integer(game.getCompletes()), - new Integer(game.getAttempts()), - new Integer(game.getPassingYards()), - new Integer(game.getPassingTd()), - new Integer(game.getInterceptions()), - new Integer(game.getRushes()), - new Integer(game.getRushYards()), - new Integer(game.getReceptions()), - new Integer(game.getReceptionYards()), - new Integer(game.getTotalTd()) }; - - this.getJdbcTemplate().update(INSERT_GAME, args); } public void clear() throws ClearFailedException { diff --git a/spring-batch-samples/src/main/java/org/springframework/batch/sample/item/writer/CustomerUpdateWriter.java b/spring-batch-samples/src/main/java/org/springframework/batch/sample/item/writer/CustomerUpdateWriter.java index a77711060..492c270a9 100644 --- a/spring-batch-samples/src/main/java/org/springframework/batch/sample/item/writer/CustomerUpdateWriter.java +++ b/spring-batch-samples/src/main/java/org/springframework/batch/sample/item/writer/CustomerUpdateWriter.java @@ -18,7 +18,6 @@ package org.springframework.batch.sample.item.writer; import org.springframework.batch.item.support.AbstractItemWriter; import org.springframework.batch.sample.dao.CustomerDebitDao; -import org.springframework.batch.sample.dao.JdbcCustomerDebitDao; import org.springframework.batch.sample.domain.CustomerDebit; import org.springframework.batch.sample.domain.Trade; @@ -29,7 +28,8 @@ import org.springframework.batch.sample.domain.Trade; * @author Robert Kasanicky */ public class CustomerUpdateWriter extends AbstractItemWriter { - private CustomerDebitDao dao; + + private CustomerDebitDao dao; public void write(Object data) { Trade trade = (Trade) data; @@ -39,7 +39,7 @@ public class CustomerUpdateWriter extends AbstractItemWriter { dao.write(customerDebit); } - public void setDao(JdbcCustomerDebitDao outputSource) { + public void setDao(CustomerDebitDao outputSource) { this.dao = outputSource; } } diff --git a/spring-batch-samples/src/main/resources/jobs/skipSampleJob.xml b/spring-batch-samples/src/main/resources/jobs/skipSampleJob.xml index 2e921d1b4..b245247a2 100644 --- a/spring-batch-samples/src/main/resources/jobs/skipSampleJob.xml +++ b/spring-batch-samples/src/main/resources/jobs/skipSampleJob.xml @@ -33,7 +33,7 @@ - + diff --git a/spring-batch-samples/src/main/resources/jobs/tradeJobIo.xml b/spring-batch-samples/src/main/resources/jobs/tradeJobIo.xml index 002d6a41c..5224d49c4 100644 --- a/spring-batch-samples/src/main/resources/jobs/tradeJobIo.xml +++ b/spring-batch-samples/src/main/resources/jobs/tradeJobIo.xml @@ -1,65 +1,65 @@ - - + + http://www.springframework.org/schema/aop/spring-aop-2.5.xsd"> - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/spring-batch-samples/src/test/java/org/springframework/batch/sample/AbstractBatchLauncherTests.java b/spring-batch-samples/src/test/java/org/springframework/batch/sample/AbstractBatchLauncherTests.java index 9cf66065c..a9d78e13f 100644 --- a/spring-batch-samples/src/test/java/org/springframework/batch/sample/AbstractBatchLauncherTests.java +++ b/spring-batch-samples/src/test/java/org/springframework/batch/sample/AbstractBatchLauncherTests.java @@ -21,6 +21,12 @@ import org.springframework.batch.core.JobParameters; import org.springframework.batch.core.launch.JobLauncher; import org.springframework.test.AbstractDependencyInjectionSpringContextTests; import org.springframework.util.ClassUtils; +import org.springframework.context.ApplicationContext; +import org.springframework.context.ApplicationContextAware; +import org.springframework.beans.factory.annotation.Autowired; +import org.apache.commons.logging.LogFactory; +import org.apache.commons.logging.Log; +import org.junit.Test; /** * Abstract unit test for running functional tests by getting context locations @@ -31,42 +37,34 @@ import org.springframework.util.ClassUtils; * @author Lucas Ward * */ -public abstract class AbstractBatchLauncherTests extends - AbstractDependencyInjectionSpringContextTests { +public abstract class AbstractBatchLauncherTests implements ApplicationContextAware { -// private static final String CONTAINER_DEFINITION_LOCATION = "simple-container-definition.xml"; + /** Logger */ + protected final Log logger = LogFactory.getLog(getClass()); - public AbstractBatchLauncherTests() { - setDependencyCheck(false); - } - - /* - * (non-Javadoc) - * @see org.springframework.test.AbstractSingleSpringContextTests#getConfigLocations() - */ - protected String[] getConfigLocations() { - return new String[] { ClassUtils.addResourcePathToPackagePath(getClass(), ClassUtils.getShortName(getClass()) - + "-context.xml") }; - } + protected ApplicationContext applicationContext; + + protected JobLauncher launcher; - JobLauncher launcher; 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; } - /** - * Public setter for the {@link Job} property. - * - * @param job the job to set - */ + @Autowired public void setJob(Job job) { this.job = job; } - + public Job getJob() { return job; } @@ -79,10 +77,7 @@ public abstract class AbstractBatchLauncherTests extends this.jobParameters = jobParameters; } - /** - * @throws Exception - * - */ + @Test public void testLaunchJob() throws Exception { launcher.run(job, jobParameters); } diff --git a/spring-batch-samples/src/test/java/org/springframework/batch/sample/AbstractCustomerCreditIncreaseTests.java b/spring-batch-samples/src/test/java/org/springframework/batch/sample/AbstractCustomerCreditIncreaseTests.java index 912b4acf9..41f9cf11f 100644 --- a/spring-batch-samples/src/test/java/org/springframework/batch/sample/AbstractCustomerCreditIncreaseTests.java +++ b/spring-batch-samples/src/test/java/org/springframework/batch/sample/AbstractCustomerCreditIncreaseTests.java @@ -1,5 +1,6 @@ package org.springframework.batch.sample; +import static org.junit.Assert.assertEquals; import java.math.BigDecimal; import java.sql.ResultSet; import java.sql.SQLException; @@ -9,10 +10,14 @@ import java.util.List; import org.springframework.batch.sample.item.writer.CustomerCreditIncreaseWriter; import org.springframework.jdbc.core.JdbcOperations; import org.springframework.jdbc.core.RowMapper; +import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.transaction.PlatformTransactionManager; import org.springframework.transaction.TransactionStatus; import org.springframework.transaction.support.TransactionCallback; import org.springframework.transaction.support.TransactionTemplate; +import org.springframework.beans.factory.annotation.Autowired; + +import javax.sql.DataSource; /** * Test case for jobs that are expected to update customer credit value by fixed @@ -44,17 +49,12 @@ public abstract class AbstractCustomerCreditIncreaseTests extends AbstractValida private List creditsBeforeUpdate; - /** - * @param jdbcTemplate - */ - public void setJdbcTemplate(JdbcOperations jdbcTemplate) { - this.jdbcTemplate = jdbcTemplate; + @Autowired + public void setDataSource(DataSource dataSource) { + this.jdbcTemplate = new JdbcTemplate(dataSource); } - - /** - * Public setter for the PlatformTransactionManager. - * @param transactionManager the transactionManager to set - */ + + @Autowired public void setTransactionManager(PlatformTransactionManager transactionManager) { this.transactionManager = transactionManager; } @@ -87,8 +87,8 @@ public abstract class AbstractCustomerCreditIncreaseTests extends AbstractValida public Object doInTransaction(TransactionStatus status) { jdbcTemplate.update(DELETE_CUSTOMERS); - for(int i = 0; i < customers.length;i++){ - jdbcTemplate.update(customers[i]); + for (String customer : customers) { + jdbcTemplate.update(customer); } return null; } @@ -108,7 +108,7 @@ public abstract class AbstractCustomerCreditIncreaseTests extends AbstractValida jdbcTemplate.query(ALL_CUSTOMERS, new RowMapper() { public Object mapRow(ResultSet rs, int rowNum) throws SQLException { - final BigDecimal creditBeforeUpdate = (BigDecimal) creditsBeforeUpdate.get(rowNum); + final BigDecimal creditBeforeUpdate = creditsBeforeUpdate.get(rowNum); System.out.print("BEFORE:" + creditBeforeUpdate); final BigDecimal expectedCredit = creditBeforeUpdate.add(CREDIT_INCREASE); System.out.print(" EXPECTED:" + expectedCredit); @@ -128,9 +128,6 @@ public abstract class AbstractCustomerCreditIncreaseTests extends AbstractValida checkMatches(matches); } - /** - * @param matches - */ protected void checkMatches(List matches) { // no-op... } diff --git a/spring-batch-samples/src/test/java/org/springframework/batch/sample/AbstractValidatingBatchLauncherTests.java b/spring-batch-samples/src/test/java/org/springframework/batch/sample/AbstractValidatingBatchLauncherTests.java index 6b79c1e12..338e2dd5e 100644 --- a/spring-batch-samples/src/test/java/org/springframework/batch/sample/AbstractValidatingBatchLauncherTests.java +++ b/spring-batch-samples/src/test/java/org/springframework/batch/sample/AbstractValidatingBatchLauncherTests.java @@ -16,19 +16,24 @@ package org.springframework.batch.sample; -import org.springframework.test.AbstractDependencyInjectionSpringContextTests; +import org.junit.Test; /** * Abstract TestCase that automatically starts a Spring (@link Lifecycle) after - * obtaining it automatically via autowiring by type. It should be noted the - * getConfigLocations must be implemented for dependency injection to work - * properly. - * + * 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 - * @see AbstractDependencyInjectionSpringContextTests + * @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(); @@ -37,12 +42,14 @@ public abstract class AbstractValidatingBatchLauncherTests extends AbstractBatch /** * 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; diff --git a/spring-batch-samples/src/test/java/org/springframework/batch/sample/BatchSqlUpdateJobFunctionalTests.java b/spring-batch-samples/src/test/java/org/springframework/batch/sample/BatchSqlUpdateJobFunctionalTests.java index d5052eaf2..b888c628e 100644 --- a/spring-batch-samples/src/test/java/org/springframework/batch/sample/BatchSqlUpdateJobFunctionalTests.java +++ b/spring-batch-samples/src/test/java/org/springframework/batch/sample/BatchSqlUpdateJobFunctionalTests.java @@ -1,10 +1,16 @@ package org.springframework.batch.sample; +import org.junit.runner.RunWith; +import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; +import org.springframework.test.context.ContextConfiguration; + /** * Test for BatchSqlUpdateJob - checks that customer credit has been updated to expected value. * * @author Robert Kasanicky */ +@RunWith(SpringJUnit4ClassRunner.class) +@ContextConfiguration() public class BatchSqlUpdateJobFunctionalTests extends AbstractCustomerCreditIncreaseTests { } diff --git a/spring-batch-samples/src/test/java/org/springframework/batch/sample/BeanWrapperMapperSampleJobFunctionalTests.java b/spring-batch-samples/src/test/java/org/springframework/batch/sample/BeanWrapperMapperSampleJobFunctionalTests.java index d24d41bb6..33a3c70cb 100644 --- a/spring-batch-samples/src/test/java/org/springframework/batch/sample/BeanWrapperMapperSampleJobFunctionalTests.java +++ b/spring-batch-samples/src/test/java/org/springframework/batch/sample/BeanWrapperMapperSampleJobFunctionalTests.java @@ -16,7 +16,13 @@ package org.springframework.batch.sample; +import org.junit.runner.RunWith; +import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; +import org.springframework.test.context.ContextConfiguration; + +@RunWith(SpringJUnit4ClassRunner.class) +@ContextConfiguration() public class BeanWrapperMapperSampleJobFunctionalTests extends AbstractValidatingBatchLauncherTests { protected void validatePostConditions() { diff --git a/spring-batch-samples/src/test/java/org/springframework/batch/sample/CompositeItemWriterSampleFunctionalTests.java b/spring-batch-samples/src/test/java/org/springframework/batch/sample/CompositeItemWriterSampleFunctionalTests.java index c524d0a50..6ad4a44b2 100644 --- a/spring-batch-samples/src/test/java/org/springframework/batch/sample/CompositeItemWriterSampleFunctionalTests.java +++ b/spring-batch-samples/src/test/java/org/springframework/batch/sample/CompositeItemWriterSampleFunctionalTests.java @@ -1,7 +1,19 @@ package org.springframework.batch.sample; +import static org.junit.Assert.assertEquals; + +import org.apache.commons.io.IOUtils; +import org.junit.runner.RunWith; +import org.springframework.batch.sample.domain.Trade; +import org.springframework.jdbc.core.JdbcOperations; +import org.springframework.jdbc.core.RowCallbackHandler; +import org.springframework.jdbc.core.JdbcTemplate; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; +import org.springframework.beans.factory.annotation.Autowired; + +import javax.sql.DataSource; import java.io.FileInputStream; -import java.io.FileNotFoundException; import java.io.IOException; import java.math.BigDecimal; import java.sql.ResultSet; @@ -9,12 +21,9 @@ import java.sql.SQLException; import java.util.ArrayList; import java.util.List; -import org.apache.commons.io.IOUtils; -import org.springframework.batch.sample.domain.Trade; -import org.springframework.jdbc.core.JdbcOperations; -import org.springframework.jdbc.core.RowCallbackHandler; - +@RunWith(SpringJUnit4ClassRunner.class) +@ContextConfiguration() public class CompositeItemWriterSampleFunctionalTests extends AbstractValidatingBatchLauncherTests { private static final String GET_TRADES = "SELECT isin, quantity, price, customer FROM trade order by isin"; @@ -32,6 +41,11 @@ public class CompositeItemWriterSampleFunctionalTests extends AbstractValidating private int before; + @Autowired + public void setDataSource(DataSource dataSource) { + this.jdbcTemplate = new JdbcTemplate(dataSource); + } + /* (non-Javadoc) * @see org.springframework.batch.sample.AbstractLifecycleSpringContextTests#validatePreConditions() */ @@ -60,7 +74,7 @@ public class CompositeItemWriterSampleFunctionalTests extends AbstractValidating jdbcTemplate.query(GET_TRADES, new RowCallbackHandler() { public void processRow(ResultSet rs) throws SQLException { - Trade trade = (Trade)trades.get(activeRow++); + Trade trade = trades.get(activeRow++); assertEquals(trade.getIsin(), rs.getString(1)); assertEquals(trade.getQuantity(), rs.getLong(2)); @@ -72,7 +86,7 @@ public class CompositeItemWriterSampleFunctionalTests extends AbstractValidating } @SuppressWarnings("unchecked") - private void checkOutputFile() throws FileNotFoundException, IOException { + private void checkOutputFile() throws IOException { List outputLines = IOUtils.readLines( new FileInputStream("target/test-outputs/20070122.testStream.ParallelCustomerReportStep.TEMP.txt")); diff --git a/spring-batch-samples/src/test/java/org/springframework/batch/sample/DelegatingJobFunctionalTests.java b/spring-batch-samples/src/test/java/org/springframework/batch/sample/DelegatingJobFunctionalTests.java index b05a2ec4d..76e6e6835 100644 --- a/spring-batch-samples/src/test/java/org/springframework/batch/sample/DelegatingJobFunctionalTests.java +++ b/spring-batch-samples/src/test/java/org/springframework/batch/sample/DelegatingJobFunctionalTests.java @@ -1,9 +1,19 @@ package org.springframework.batch.sample; -import org.springframework.batch.sample.domain.PersonService; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; +import org.springframework.batch.sample.domain.PersonService; +import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.beans.factory.annotation.Autowired; +import org.junit.runner.RunWith; + +@RunWith(SpringJUnit4ClassRunner.class) +@ContextConfiguration() public class DelegatingJobFunctionalTests extends AbstractValidatingBatchLauncherTests { + @Autowired private PersonService personService; protected void validatePostConditions() throws Exception { @@ -11,11 +21,5 @@ public class DelegatingJobFunctionalTests extends AbstractValidatingBatchLaunche assertEquals(personService.getReturnedCount(), personService.getReceivedCount()); } - - // setter for auto-injection - public void setPersonService(PersonService personService) { - this.personService = personService; - } - } diff --git a/spring-batch-samples/src/test/java/org/springframework/batch/sample/FixedLengthImportJobFunctionalTests.java b/spring-batch-samples/src/test/java/org/springframework/batch/sample/FixedLengthImportJobFunctionalTests.java index 1ce1232e2..310a40f19 100644 --- a/spring-batch-samples/src/test/java/org/springframework/batch/sample/FixedLengthImportJobFunctionalTests.java +++ b/spring-batch-samples/src/test/java/org/springframework/batch/sample/FixedLengthImportJobFunctionalTests.java @@ -16,6 +16,8 @@ package org.springframework.batch.sample; +import static org.junit.Assert.*; + import java.io.BufferedReader; import java.io.FileReader; import java.sql.ResultSet; @@ -30,7 +32,17 @@ import org.springframework.core.io.ClassPathResource; import org.springframework.core.io.Resource; import org.springframework.jdbc.core.JdbcOperations; import org.springframework.jdbc.core.RowCallbackHandler; +import org.springframework.jdbc.core.JdbcTemplate; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; +import org.springframework.test.context.ContextConfiguration; +import org.junit.Before; +import org.junit.runner.RunWith; +import javax.sql.DataSource; + +@RunWith(SpringJUnit4ClassRunner.class) +@ContextConfiguration() public class FixedLengthImportJobFunctionalTests extends AbstractValidatingBatchLauncherTests { //expected line length in input file (sum of pattern lengths + 2, because the counter is appended twice) @@ -42,8 +54,19 @@ public class FixedLengthImportJobFunctionalTests extends AbstractValidatingBatch private FlatFileItemReader inputSource; private LineTokenizer lineTokenizer; - protected void onSetUp() throws Exception { - super.onSetUp(); + @Autowired + public void setDataSource(DataSource dataSource) { + this.jdbcTemplate = new JdbcTemplate(dataSource); + } + + @Autowired + public void setLineTokenizer(LineTokenizer lineTokenizer) { + this.lineTokenizer = lineTokenizer; + } + + + @Before + public void onSetUp() throws Exception { jdbcTemplate.update("delete from TRADE"); fileLocator = new ClassPathResource("data/fixedLengthImportJob/input/20070122.teststream.ImportTradeDataStep.txt"); inputSource = new FlatFileItemReader(); @@ -94,12 +117,4 @@ public class FixedLengthImportJobFunctionalTests extends AbstractValidatingBatch } } - public void setJdbcTemplate(JdbcOperations jdbcTemplate) { - this.jdbcTemplate = jdbcTemplate; - } - - public void setLineTokenizer(LineTokenizer lineTokenizer) { - this.lineTokenizer = lineTokenizer; - } - } diff --git a/spring-batch-samples/src/test/java/org/springframework/batch/sample/FootballJobFunctionalTests.java b/spring-batch-samples/src/test/java/org/springframework/batch/sample/FootballJobFunctionalTests.java index fdd9b9d60..f335e3063 100644 --- a/spring-batch-samples/src/test/java/org/springframework/batch/sample/FootballJobFunctionalTests.java +++ b/spring-batch-samples/src/test/java/org/springframework/batch/sample/FootballJobFunctionalTests.java @@ -1,15 +1,23 @@ package org.springframework.batch.sample; +import static org.junit.Assert.*; +import org.junit.runner.RunWith; + import javax.sql.DataSource; import org.springframework.jdbc.core.JdbcOperations; import org.springframework.jdbc.core.JdbcTemplate; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; +import org.springframework.beans.factory.annotation.Autowired; -public class FootballJobFunctionalTests extends - AbstractValidatingBatchLauncherTests { +@RunWith(SpringJUnit4ClassRunner.class) +@ContextConfiguration() +public class FootballJobFunctionalTests extends AbstractValidatingBatchLauncherTests { private JdbcOperations jdbcTemplate; + @Autowired public void setDataSource(DataSource dataSource) { this.jdbcTemplate = new JdbcTemplate(dataSource); } diff --git a/spring-batch-samples/src/test/java/org/springframework/batch/sample/GracefulShutdownFunctionalTests.java b/spring-batch-samples/src/test/java/org/springframework/batch/sample/GracefulShutdownFunctionalTests.java index 24f48dd75..0c29815c5 100644 --- a/spring-batch-samples/src/test/java/org/springframework/batch/sample/GracefulShutdownFunctionalTests.java +++ b/spring-batch-samples/src/test/java/org/springframework/batch/sample/GracefulShutdownFunctionalTests.java @@ -16,9 +16,16 @@ package org.springframework.batch.sample; +import static org.junit.Assert.*; + import org.springframework.batch.core.BatchStatus; import org.springframework.batch.core.JobExecution; import org.springframework.batch.core.JobParameters; +import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.transaction.annotation.Transactional; +import org.junit.runner.RunWith; +import org.junit.Test; /** * Functional test for graceful shutdown. A batch container is started in a new thread, @@ -27,8 +34,11 @@ import org.springframework.batch.core.JobParameters; * @author Lucas Ward * */ +@RunWith(SpringJUnit4ClassRunner.class) +@ContextConfiguration() public class GracefulShutdownFunctionalTests extends AbstractBatchLauncherTests { + @Transactional @Test public void testLaunchJob() throws Exception { final JobParameters jobParameters = new JobParameters(); diff --git a/spring-batch-samples/src/test/java/org/springframework/batch/sample/HibernateFailureJobFunctionalTests.java b/spring-batch-samples/src/test/java/org/springframework/batch/sample/HibernateFailureJobFunctionalTests.java index b5da86825..050e73b54 100644 --- a/spring-batch-samples/src/test/java/org/springframework/batch/sample/HibernateFailureJobFunctionalTests.java +++ b/spring-batch-samples/src/test/java/org/springframework/batch/sample/HibernateFailureJobFunctionalTests.java @@ -1,13 +1,21 @@ package org.springframework.batch.sample; -import java.math.BigDecimal; -import java.util.List; +import static org.junit.Assert.*; +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.dao.HibernateCreditDao; +import org.springframework.beans.factory.annotation.Autowired; import org.springframework.jdbc.UncategorizedSQLException; import org.springframework.orm.hibernate3.HibernateJdbcException; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; +import org.springframework.transaction.annotation.Transactional; + +import java.math.BigDecimal; +import java.util.List; /** * Test for HibernateJob - checks that customer credit has been updated to @@ -15,8 +23,9 @@ import org.springframework.orm.hibernate3.HibernateJdbcException; * * @author Dave Syer */ -public class HibernateFailureJobFunctionalTests extends - HibernateJobFunctionalTests { +@RunWith(SpringJUnit4ClassRunner.class) +@ContextConfiguration() +public class HibernateFailureJobFunctionalTests extends AbstractCustomerCreditIncreaseTests { private HibernateCreditDao writer; @@ -26,25 +35,12 @@ public class HibernateFailureJobFunctionalTests extends * @param writer * the writer to set */ + @Autowired public void setWriter(HibernateCreditDao writer) { this.writer = writer; } - /* - * (non-Javadoc) - * - * @see org.springframework.test.AbstractSingleSpringContextTests#onTearDown() - */ - protected void onTearDown() throws Exception { - super.onTearDown(); - writer.setFailOnFlush(-1); - } - - /* - * (non-Javadoc) - * - * @see org.springframework.batch.sample.AbstractValidatingBatchLauncherTests#testLaunchJob() - */ + @Transactional @Test public void testLaunchJob() throws Exception { JobParameters params = new JobParametersBuilder().addString("key", "failureJob").toJobParameters(); setJobParameters(params); diff --git a/spring-batch-samples/src/test/java/org/springframework/batch/sample/HibernateJobFunctionalTests.java b/spring-batch-samples/src/test/java/org/springframework/batch/sample/HibernateJobFunctionalTests.java index e40c0a16a..2884bb5ca 100644 --- a/spring-batch-samples/src/test/java/org/springframework/batch/sample/HibernateJobFunctionalTests.java +++ b/spring-batch-samples/src/test/java/org/springframework/batch/sample/HibernateJobFunctionalTests.java @@ -1,10 +1,16 @@ package org.springframework.batch.sample; +import org.junit.runner.RunWith; +import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; +import org.springframework.test.context.ContextConfiguration; + /** * Test for HibernateJob - checks that customer credit has been updated to expected value. * * @author Robert Kasanicky */ +@RunWith(SpringJUnit4ClassRunner.class) +@ContextConfiguration() public class HibernateJobFunctionalTests extends AbstractCustomerCreditIncreaseTests { } diff --git a/spring-batch-samples/src/test/java/org/springframework/batch/sample/IbatisJobFunctionalTests.java b/spring-batch-samples/src/test/java/org/springframework/batch/sample/IbatisJobFunctionalTests.java index 48dffb61f..ed1ac9ba1 100644 --- a/spring-batch-samples/src/test/java/org/springframework/batch/sample/IbatisJobFunctionalTests.java +++ b/spring-batch-samples/src/test/java/org/springframework/batch/sample/IbatisJobFunctionalTests.java @@ -1,11 +1,17 @@ package org.springframework.batch.sample; +import org.junit.runner.RunWith; +import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; +import org.springframework.test.context.ContextConfiguration; + /** * Test for IbatisJob - checks that customer credit has been updated to expected value. * * @author Robert Kasanicky */ +@RunWith(SpringJUnit4ClassRunner.class) +@ContextConfiguration() public class IbatisJobFunctionalTests extends AbstractCustomerCreditIncreaseTests{ } diff --git a/spring-batch-samples/src/test/java/org/springframework/batch/sample/JobExecutionContextSampleFunctionalTests.java b/spring-batch-samples/src/test/java/org/springframework/batch/sample/JobExecutionContextSampleFunctionalTests.java index d81cb835b..c7db883e3 100644 --- a/spring-batch-samples/src/test/java/org/springframework/batch/sample/JobExecutionContextSampleFunctionalTests.java +++ b/spring-batch-samples/src/test/java/org/springframework/batch/sample/JobExecutionContextSampleFunctionalTests.java @@ -1,26 +1,26 @@ package org.springframework.batch.sample; +import static org.junit.Assert.*; +import org.junit.runner.RunWith; + import org.springframework.batch.sample.tasklet.DummyMessageReceivingTasklet; import org.springframework.batch.sample.tasklet.DummyMessageSendingTasklet; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; +import org.springframework.beans.factory.annotation.Autowired; +@RunWith(SpringJUnit4ClassRunner.class) +@ContextConfiguration() public class JobExecutionContextSampleFunctionalTests extends AbstractValidatingBatchLauncherTests { + @Autowired private DummyMessageSendingTasklet sender; + @Autowired private DummyMessageReceivingTasklet receiver; protected void validatePostConditions() throws Exception { assertEquals(sender.getMessage(), receiver.getReceivedMessage()); } - // auto-injection setter - public void setSender(DummyMessageSendingTasklet sender) { - this.sender = sender; - } - - // auto-injection setter - public void setReceiver(DummyMessageReceivingTasklet receiver) { - this.receiver = receiver; - } - } diff --git a/spring-batch-samples/src/test/java/org/springframework/batch/sample/MultiResourceJobFunctionalTests.java b/spring-batch-samples/src/test/java/org/springframework/batch/sample/MultiResourceJobFunctionalTests.java index d5c996ec3..a0f89fb42 100644 --- a/spring-batch-samples/src/test/java/org/springframework/batch/sample/MultiResourceJobFunctionalTests.java +++ b/spring-batch-samples/src/test/java/org/springframework/batch/sample/MultiResourceJobFunctionalTests.java @@ -1,5 +1,20 @@ package org.springframework.batch.sample; +import org.junit.runner.RunWith; +import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.annotation.Qualifier; +import org.springframework.batch.core.Job; + +@RunWith(SpringJUnit4ClassRunner.class) +@ContextConfiguration() public class MultiResourceJobFunctionalTests extends FixedLengthImportJobFunctionalTests { + + @Autowired + public void setJob(@Qualifier("multiResourceJob") Job job) { + super.setJob(job); + } + } diff --git a/spring-batch-samples/src/test/java/org/springframework/batch/sample/MultilineJobFunctionalTests.java b/spring-batch-samples/src/test/java/org/springframework/batch/sample/MultilineJobFunctionalTests.java index 5a69cce72..402b86fa0 100644 --- a/spring-batch-samples/src/test/java/org/springframework/batch/sample/MultilineJobFunctionalTests.java +++ b/spring-batch-samples/src/test/java/org/springframework/batch/sample/MultilineJobFunctionalTests.java @@ -16,11 +16,18 @@ package org.springframework.batch.sample; +import static org.junit.Assert.*; + import org.apache.commons.io.IOUtils; import org.springframework.core.io.FileSystemResource; import org.springframework.core.io.Resource; import org.springframework.util.StringUtils; +import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; +import org.springframework.test.context.ContextConfiguration; +import org.junit.runner.RunWith; +@RunWith(SpringJUnit4ClassRunner.class) +@ContextConfiguration() public class MultilineJobFunctionalTests extends AbstractValidatingBatchLauncherTests { // The output is grouped together in two lines, instead of all the diff --git a/spring-batch-samples/src/test/java/org/springframework/batch/sample/MultilineOrderJobFunctionalTests.java b/spring-batch-samples/src/test/java/org/springframework/batch/sample/MultilineOrderJobFunctionalTests.java index 2176c4788..fc796a387 100644 --- a/spring-batch-samples/src/test/java/org/springframework/batch/sample/MultilineOrderJobFunctionalTests.java +++ b/spring-batch-samples/src/test/java/org/springframework/batch/sample/MultilineOrderJobFunctionalTests.java @@ -16,15 +16,21 @@ package org.springframework.batch.sample; +import static org.junit.Assert.*; +import org.junit.runner.RunWith; + import java.io.IOException; import org.apache.commons.io.IOUtils; import org.springframework.core.io.FileSystemResource; import org.springframework.core.io.Resource; import org.springframework.util.StringUtils; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; +@RunWith(SpringJUnit4ClassRunner.class) +@ContextConfiguration() public class MultilineOrderJobFunctionalTests extends AbstractValidatingBatchLauncherTests { - //private static final Log log = LogFactory.getLog(MultilineOrderJobFunctionalTests.class); private static final String EXPECTED_OUTPUT = "BEGIN_ORDER:13100345 2007/02/15 "+ diff --git a/spring-batch-samples/src/test/java/org/springframework/batch/sample/ParallelJobFunctionalTests.java b/spring-batch-samples/src/test/java/org/springframework/batch/sample/ParallelJobFunctionalTests.java index 959519fd8..d5a4f5983 100644 --- a/spring-batch-samples/src/test/java/org/springframework/batch/sample/ParallelJobFunctionalTests.java +++ b/spring-batch-samples/src/test/java/org/springframework/batch/sample/ParallelJobFunctionalTests.java @@ -1,16 +1,24 @@ package org.springframework.batch.sample; +import static org.junit.Assert.*; + import javax.sql.DataSource; import org.springframework.batch.sample.item.writer.StagingItemWriter; import org.springframework.jdbc.core.JdbcOperations; import org.springframework.jdbc.core.JdbcTemplate; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; +import org.springframework.beans.factory.annotation.Autowired; +import org.junit.runner.RunWith; -public class ParallelJobFunctionalTests extends - AbstractValidatingBatchLauncherTests { +@RunWith(SpringJUnit4ClassRunner.class) +@ContextConfiguration() +public class ParallelJobFunctionalTests extends AbstractValidatingBatchLauncherTests { private JdbcOperations jdbcTemplate; + @Autowired public void setDataSource(DataSource dataSource) { this.jdbcTemplate = new JdbcTemplate(dataSource); } diff --git a/spring-batch-samples/src/test/java/org/springframework/batch/sample/RestartFunctionalTests.java b/spring-batch-samples/src/test/java/org/springframework/batch/sample/RestartFunctionalTests.java index 886c68d49..b12f08a04 100644 --- a/spring-batch-samples/src/test/java/org/springframework/batch/sample/RestartFunctionalTests.java +++ b/spring-batch-samples/src/test/java/org/springframework/batch/sample/RestartFunctionalTests.java @@ -16,10 +16,21 @@ package org.springframework.batch.sample; +import static org.junit.Assert.*; +import org.junit.runner.RunWith; +import org.junit.Test; + import org.springframework.batch.core.UnexpectedJobExecutionException; import org.springframework.batch.core.converter.DefaultJobParametersConverter; import org.springframework.batch.support.PropertiesConverter; import org.springframework.jdbc.core.JdbcOperations; +import org.springframework.jdbc.core.JdbcTemplate; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.transaction.BeforeTransaction; +import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; +import org.springframework.beans.factory.annotation.Autowired; + +import javax.sql.DataSource; /** * Simple restart scenario. @@ -27,25 +38,25 @@ import org.springframework.jdbc.core.JdbcOperations; * @author Robert Kasanicky * @author Dave Syer */ +@RunWith(SpringJUnit4ClassRunner.class) +@ContextConfiguration() public class RestartFunctionalTests extends AbstractBatchLauncherTests { // auto-injected attributes private JdbcOperations jdbcTemplate; - /** - * Public setter for the jdbcTemplate. - * - * @param jdbcTemplate the jdbcTemplate to set - */ - public void setJdbcTemplate(JdbcOperations jdbcTemplate) { - this.jdbcTemplate = jdbcTemplate; + @Autowired + public void setDataSource(DataSource dataSource) { + this.jdbcTemplate = new JdbcTemplate(dataSource); } + /* * (non-Javadoc) * @see org.springframework.test.AbstractSingleSpringContextTests#onTearDown() */ - protected void onTearDown() throws Exception { + @BeforeTransaction + public void onTearDown() throws Exception { jdbcTemplate.update("DELETE FROM TRADE"); } @@ -55,8 +66,9 @@ public class RestartFunctionalTests extends AbstractBatchLauncherTests { * finish successfully, because it continues execution where the previous * run stopped (module throws exception after fixed number of processed * records). - * @throws Exception + * @throws Exception the exception thrown */ + @Test public void testRestart() throws Exception { int before = jdbcTemplate.queryForInt("SELECT COUNT(*) FROM TRADE"); diff --git a/spring-batch-samples/src/test/java/org/springframework/batch/sample/RetrySampleFunctionalTests.java b/spring-batch-samples/src/test/java/org/springframework/batch/sample/RetrySampleFunctionalTests.java index ae033677e..567493748 100644 --- a/spring-batch-samples/src/test/java/org/springframework/batch/sample/RetrySampleFunctionalTests.java +++ b/spring-batch-samples/src/test/java/org/springframework/batch/sample/RetrySampleFunctionalTests.java @@ -1,17 +1,27 @@ package org.springframework.batch.sample; +import static org.junit.Assert.*; +import org.junit.runner.RunWith; + import org.springframework.batch.sample.item.reader.GeneratingItemReader; import org.springframework.batch.sample.item.writer.RetrySampleItemWriter; +import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.beans.factory.annotation.Autowired; /** * Checks that expected number of items have been processed. * * @author Robert Kasanicky */ +@RunWith(SpringJUnit4ClassRunner.class) +@ContextConfiguration() public class RetrySampleFunctionalTests extends AbstractValidatingBatchLauncherTests { + @Autowired private GeneratingItemReader itemGenerator; + @Autowired private RetrySampleItemWriter itemProcessor; protected void validatePostConditions() throws Exception { @@ -19,12 +29,4 @@ public class RetrySampleFunctionalTests extends AbstractValidatingBatchLauncherT assertEquals(itemGenerator.getLimit()+2, itemProcessor.getCounter()); } - public void setItemGenerator(GeneratingItemReader itemGenerator) { - this.itemGenerator = itemGenerator; - } - - public void setItemProcessor(RetrySampleItemWriter itemProcessor) { - this.itemProcessor = itemProcessor; - } - } diff --git a/spring-batch-samples/src/test/java/org/springframework/batch/sample/SkipSampleFunctionalTests.java b/spring-batch-samples/src/test/java/org/springframework/batch/sample/SkipSampleFunctionalTests.java index 11bb52c74..ddebfd108 100644 --- a/spring-batch-samples/src/test/java/org/springframework/batch/sample/SkipSampleFunctionalTests.java +++ b/spring-batch-samples/src/test/java/org/springframework/batch/sample/SkipSampleFunctionalTests.java @@ -1,7 +1,15 @@ package org.springframework.batch.sample; +import static org.junit.Assert.assertEquals; +import org.junit.Before; +import org.junit.runner.RunWith; import org.springframework.batch.sample.item.writer.ItemTrackingItemWriter; +import org.springframework.beans.factory.annotation.Autowired; import org.springframework.jdbc.core.JdbcTemplate; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; + +import javax.sql.DataSource; /** * Error is encountered during writing - transaction is rolled back and the @@ -9,29 +17,29 @@ import org.springframework.jdbc.core.JdbcTemplate; * * @author Robert Kasanicky */ +@RunWith(SpringJUnit4ClassRunner.class) +@ContextConfiguration() public class SkipSampleFunctionalTests extends AbstractValidatingBatchLauncherTests { int before = -1; JdbcTemplate jdbcTemplate; + @Autowired ItemTrackingItemWriter writer; - // auto-injection - public void setWriter(ItemTrackingItemWriter writer) { - this.writer = writer; + @Autowired + public void setDataSource(DataSource dataSource) { + this.jdbcTemplate = new JdbcTemplate(dataSource); } - // auto-injection - public void setJdbcTemplate(JdbcTemplate jdbcTemplate) { - this.jdbcTemplate = jdbcTemplate; - } - - protected void onSetUp() throws Exception { + @Before + public void onSetUp() throws Exception { before = jdbcTemplate.queryForInt("SELECT COUNT(*) from TRADE"); } protected void validatePostConditions() throws Exception { + int after = jdbcTemplate.queryForInt("SELECT COUNT(*) from TRADE"); // 5 input records, 1 skipped => 4 written to output assertEquals(before + 4, after); diff --git a/spring-batch-samples/src/test/java/org/springframework/batch/sample/TaskletJobFunctionalTests.java b/spring-batch-samples/src/test/java/org/springframework/batch/sample/TaskletJobFunctionalTests.java index 3c07a921a..ca07c465d 100644 --- a/spring-batch-samples/src/test/java/org/springframework/batch/sample/TaskletJobFunctionalTests.java +++ b/spring-batch-samples/src/test/java/org/springframework/batch/sample/TaskletJobFunctionalTests.java @@ -4,27 +4,29 @@ import java.io.File; import org.springframework.core.io.Resource; import org.springframework.util.Assert; +import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.beans.factory.annotation.Autowired; +import org.junit.runner.RunWith; +import org.junit.Before; /** * Deletes files in the given directory. * * @author Robert Kasanicky */ +@RunWith(SpringJUnit4ClassRunner.class) +@ContextConfiguration() public class TaskletJobFunctionalTests extends AbstractValidatingBatchLauncherTests { + @Autowired private Resource directory; - /** - * Setter for auto-injection. - */ - public void setDirectory(Resource directory) { - this.directory = directory; - } - /** * Create the directory and some files in it. */ - protected void onSetUp() throws Exception { + @Before + public void onSetUp() throws Exception { File dir = directory.getFile(); dir.mkdirs(); new File(dir, "file1").createNewFile(); @@ -34,6 +36,7 @@ public class TaskletJobFunctionalTests extends AbstractValidatingBatchLauncherTe /** * We have directory with some files in it. */ + @Override protected void validatePreConditions() throws Exception { Assert.state(directory.getFile().isDirectory()); Assert.state(directory.getFile().listFiles().length > 0); @@ -42,6 +45,7 @@ public class TaskletJobFunctionalTests extends AbstractValidatingBatchLauncherTe /** * Directory still exists but contains no files. */ + @Override protected void validatePostConditions() throws Exception { Assert.state(directory.getFile().isDirectory()); Assert.state(directory.getFile().listFiles().length == 0); diff --git a/spring-batch-samples/src/test/java/org/springframework/batch/sample/TradeJobFunctionalTests.java b/spring-batch-samples/src/test/java/org/springframework/batch/sample/TradeJobFunctionalTests.java index 7e5a2f6ce..ca090293c 100644 --- a/spring-batch-samples/src/test/java/org/springframework/batch/sample/TradeJobFunctionalTests.java +++ b/spring-batch-samples/src/test/java/org/springframework/batch/sample/TradeJobFunctionalTests.java @@ -16,6 +16,8 @@ package org.springframework.batch.sample; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; import java.math.BigDecimal; import java.sql.ResultSet; import java.sql.SQLException; @@ -30,9 +32,20 @@ import org.springframework.core.io.FileSystemResource; import org.springframework.core.io.Resource; import org.springframework.jdbc.core.JdbcOperations; import org.springframework.jdbc.core.RowCallbackHandler; +import org.springframework.jdbc.core.JdbcTemplate; +import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.transaction.annotation.Transactional; +import org.springframework.beans.factory.annotation.Autowired; +import org.junit.runner.RunWith; +import org.junit.Test; +import org.junit.Before; + +import javax.sql.DataSource; - +@RunWith(SpringJUnit4ClassRunner.class) +@ContextConfiguration() public class TradeJobFunctionalTests extends AbstractValidatingBatchLauncherTests { private static final String GET_TRADES = "select ISIN, QUANTITY, PRICE, CUSTOMER from TRADE order by ISIN"; @@ -44,20 +57,16 @@ public class TradeJobFunctionalTests extends AbstractValidatingBatchLauncherTest private JdbcOperations jdbcTemplate; private Map credits = new HashMap(); - - /** - * @param jdbcTemplate the jdbcTemplate to set - */ - public void setJdbcTemplate(JdbcOperations jdbcTemplate) { - this.jdbcTemplate = jdbcTemplate; + + @Autowired + public void setDataSource(DataSource dataSource) { + this.jdbcTemplate = new JdbcTemplate(dataSource); } - /* (non-Javadoc) - * @see org.springframework.test.AbstractSingleSpringContextTests#onSetUp() - */ @SuppressWarnings("unchecked") - protected void onSetUp() throws Exception { - super.onSetUp(); + @Before + public void onSetUp() throws Exception { +// super.onSetUp(); jdbcTemplate.update("delete from TRADE"); List> list = jdbcTemplate.queryForList("select name, CREDIT from customer"); for (Iterator> iterator = list.iterator(); iterator.hasNext();) { @@ -66,6 +75,7 @@ public class TradeJobFunctionalTests extends AbstractValidatingBatchLauncherTest } } + @Transactional @Test public void testLaunchJob() throws Exception{ super.testLaunchJob(); } @@ -123,7 +133,7 @@ public class TradeJobFunctionalTests extends AbstractValidatingBatchLauncherTest protected void validatePreConditions() { assertTrue(((Resource)applicationContext.getBean("fileLocator")).exists()); } - + private static class Customer { private String name; private double credit; diff --git a/spring-batch-samples/src/test/java/org/springframework/batch/sample/XmlStaxJobFunctionalTests.java b/spring-batch-samples/src/test/java/org/springframework/batch/sample/XmlStaxJobFunctionalTests.java index 0b38435e8..1eb58fa69 100644 --- a/spring-batch-samples/src/test/java/org/springframework/batch/sample/XmlStaxJobFunctionalTests.java +++ b/spring-batch-samples/src/test/java/org/springframework/batch/sample/XmlStaxJobFunctionalTests.java @@ -20,8 +20,13 @@ import java.io.FileReader; import org.custommonkey.xmlunit.XMLAssert; import org.custommonkey.xmlunit.XMLUnit; +import org.junit.runner.RunWith; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; +@RunWith(SpringJUnit4ClassRunner.class) +@ContextConfiguration() public class XmlStaxJobFunctionalTests extends AbstractValidatingBatchLauncherTests { private static final String OUTPUT_FILE = "target/test-outputs/20070918.testStream.xmlFileStep.output.xml"; diff --git a/spring-batch-samples/src/test/java/org/springframework/batch/sample/advice/JobExecutionNotificationPublisherTests.java b/spring-batch-samples/src/test/java/org/springframework/batch/sample/advice/JobExecutionNotificationPublisherTests.java index 1e077f63f..0cbe42e8a 100644 --- a/spring-batch-samples/src/test/java/org/springframework/batch/sample/advice/JobExecutionNotificationPublisherTests.java +++ b/spring-batch-samples/src/test/java/org/springframework/batch/sample/advice/JobExecutionNotificationPublisherTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2006-2007 the original author or authors. + * Copyright 2006-2008 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. @@ -15,24 +15,27 @@ */ package org.springframework.batch.sample.advice; -import java.util.ArrayList; -import java.util.List; - -import javax.management.Notification; - -import junit.framework.TestCase; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; +import org.junit.Test; import org.springframework.jmx.export.notification.NotificationPublisher; import org.springframework.jmx.export.notification.UnableToSendNotificationException; +import javax.management.Notification; +import java.util.ArrayList; +import java.util.List; + /** * @author Dave Syer - * + * @author Thomas Risberg + * */ -public class JobExecutionNotificationPublisherTests extends TestCase { +public class JobExecutionNotificationPublisherTests { JobExecutionNotificationPublisher publisher = new JobExecutionNotificationPublisher(); + @Test public void testRepeatOperationsOpenUsed() throws Exception { final List list = new ArrayList(); publisher.setNotificationPublisher(new NotificationPublisher() { diff --git a/spring-batch-samples/src/test/java/org/springframework/batch/sample/dao/FlatFileCustomerCreditDaoTests.java b/spring-batch-samples/src/test/java/org/springframework/batch/sample/dao/FlatFileCustomerCreditDaoTests.java index 0038b08d0..b5cf43fdb 100644 --- a/spring-batch-samples/src/test/java/org/springframework/batch/sample/dao/FlatFileCustomerCreditDaoTests.java +++ b/spring-batch-samples/src/test/java/org/springframework/batch/sample/dao/FlatFileCustomerCreditDaoTests.java @@ -1,59 +1,77 @@ +/* + * Copyright 2006-2008 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.dao; -import java.math.BigDecimal; +import static org.easymock.EasyMock.*; -import junit.framework.TestCase; - -import org.easymock.MockControl; +import org.junit.Before; +import org.junit.Test; import org.springframework.batch.item.ExecutionContext; import org.springframework.batch.item.ItemStream; import org.springframework.batch.item.ItemWriter; import org.springframework.batch.sample.domain.CustomerCredit; -public class FlatFileCustomerCreditDaoTests extends TestCase { +import java.math.BigDecimal; - private MockControl outputControl; +public class FlatFileCustomerCreditDaoTests { + + //private MockControl outputControl; private ResourceLifecycleItemWriter output; private FlatFileCustomerCreditDao writer; + @Before public void setUp() throws Exception { - super.setUp(); - + //create mock for OutputSource - outputControl = MockControl.createControl(ResourceLifecycleItemWriter.class); - output = (ResourceLifecycleItemWriter)outputControl.getMock(); - + output = createMock(ResourceLifecycleItemWriter.class); + //create new writer writer = new FlatFileCustomerCreditDao(); writer.setItemWriter(output); } + @Test public void testOpen() throws Exception { ExecutionContext executionContext = new ExecutionContext(); //set-up outputSource mock output.open(executionContext); - outputControl.replay(); - + replay(output); + //call tested method writer.open(executionContext); //verify method calls - outputControl.verify(); + verify(output); } + @Test public void testClose() throws Exception{ //set-up outputSource mock output.close(null); - outputControl.replay(); - + replay(output); + //call tested method writer.close(); //verify method calls - outputControl.verify(); + verify(output); } + @Test public void testWrite() throws Exception { //Create and set-up CustomerCredit @@ -67,13 +85,13 @@ public class FlatFileCustomerCreditDaoTests extends TestCase { //set-up OutputSource mock output.write("testName;1"); output.open(new ExecutionContext()); - outputControl.replay(); - + replay(output); + //call tested method writer.writeCredit(credit); //verify method calls - outputControl.verify(); + verify(output); } private interface ResourceLifecycleItemWriter extends ItemWriter, ItemStream{ diff --git a/spring-batch-samples/src/test/java/org/springframework/batch/sample/dao/FlatFileOrderWriterTests.java b/spring-batch-samples/src/test/java/org/springframework/batch/sample/dao/FlatFileOrderWriterTests.java index 1073b8f0f..1c4641585 100644 --- a/spring-batch-samples/src/test/java/org/springframework/batch/sample/dao/FlatFileOrderWriterTests.java +++ b/spring-batch-samples/src/test/java/org/springframework/batch/sample/dao/FlatFileOrderWriterTests.java @@ -1,5 +1,23 @@ +/* + * Copyright 2006-2008 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.dao; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; + import java.math.BigDecimal; import java.util.ArrayList; import java.util.GregorianCalendar; @@ -18,8 +36,10 @@ import org.springframework.batch.sample.domain.BillingInfo; import org.springframework.batch.sample.domain.Customer; import org.springframework.batch.sample.domain.LineItem; import org.springframework.batch.sample.domain.Order; +import org.junit.Before; +import org.junit.Test; -public class FlatFileOrderWriterTests extends TestCase { +public class FlatFileOrderWriterTests { List list = new ArrayList(); @@ -31,13 +51,14 @@ public class FlatFileOrderWriterTests extends TestCase { private FlatFileOrderWriter writer; + @Before public void setUp() throws Exception { - super.setUp(); //create new writer writer = new FlatFileOrderWriter(); writer.setDelegate(output); } + @Test public void testWrite() throws Exception { //Create and set-up Order diff --git a/spring-batch-samples/src/test/java/org/springframework/batch/sample/dao/JdbcCustomerDebitDaoTests.java b/spring-batch-samples/src/test/java/org/springframework/batch/sample/dao/JdbcCustomerDebitDaoTests.java index 16a2900b5..13261fb22 100644 --- a/spring-batch-samples/src/test/java/org/springframework/batch/sample/dao/JdbcCustomerDebitDaoTests.java +++ b/spring-batch-samples/src/test/java/org/springframework/batch/sample/dao/JdbcCustomerDebitDaoTests.java @@ -1,27 +1,55 @@ +/* + * Copyright 2006-2008 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.dao; +import static org.junit.Assert.assertEquals; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.batch.sample.domain.CustomerDebit; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.jdbc.core.RowCallbackHandler; +import org.springframework.jdbc.core.simple.SimpleJdbcTemplate; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; +import org.springframework.transaction.annotation.Transactional; + +import javax.sql.DataSource; import java.math.BigDecimal; import java.sql.ResultSet; import java.sql.SQLException; -import org.springframework.batch.sample.domain.CustomerDebit; -import org.springframework.jdbc.core.RowCallbackHandler; -import org.springframework.test.AbstractTransactionalDataSourceSpringContextTests; +@RunWith(SpringJUnit4ClassRunner.class) +@ContextConfiguration() +public class JdbcCustomerDebitDaoTests { -public class JdbcCustomerDebitDaoTests extends AbstractTransactionalDataSourceSpringContextTests { + private SimpleJdbcTemplate simpleJdbcTemplate; - protected String[] getConfigLocations() { - return new String[] { "data-source-context.xml" }; + @Autowired + private JdbcCustomerDebitDao writer; + + @Autowired + public void setDataSource(DataSource dataSource) { + this.simpleJdbcTemplate = new SimpleJdbcTemplate(dataSource); } + @Transactional @Test public void testWrite() { //insert customer credit - jdbcTemplate.execute("INSERT INTO customer VALUES (99, 0, 'testName', 100)"); - - //create writer and set jdbcTemplate - JdbcCustomerDebitDao writer = new JdbcCustomerDebitDao(); - writer.setJdbcTemplate(jdbcTemplate); + simpleJdbcTemplate.getJdbcOperations().execute("INSERT INTO customer VALUES (99, 0, 'testName', 100)"); //create customer debit CustomerDebit customerDebit = new CustomerDebit(); @@ -32,11 +60,12 @@ public class JdbcCustomerDebitDaoTests extends AbstractTransactionalDataSourceSp writer.write(customerDebit); //verify customer credit - jdbcTemplate.query("SELECT name, credit FROM customer WHERE name = 'testName'", new RowCallbackHandler() { - public void processRow(ResultSet rs) throws SQLException { - assertEquals(95, rs.getLong("credit")); - } - }); + simpleJdbcTemplate.getJdbcOperations().query("SELECT name, credit FROM customer WHERE name = 'testName'", + new RowCallbackHandler() { + public void processRow(ResultSet rs) throws SQLException { + assertEquals(95, rs.getLong("credit")); + } + }); } } diff --git a/spring-batch-samples/src/test/java/org/springframework/batch/sample/dao/JdbcGameDaoIntegrationTests.java b/spring-batch-samples/src/test/java/org/springframework/batch/sample/dao/JdbcGameDaoIntegrationTests.java index e57a309c0..a2657da55 100644 --- a/spring-batch-samples/src/test/java/org/springframework/batch/sample/dao/JdbcGameDaoIntegrationTests.java +++ b/spring-batch-samples/src/test/java/org/springframework/batch/sample/dao/JdbcGameDaoIntegrationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2006-2007 the original author or authors. + * Copyright 2006-2008 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. @@ -15,32 +15,46 @@ */ package org.springframework.batch.sample.dao; +import static org.junit.Assert.assertEquals; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.batch.sample.domain.Game; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.jdbc.core.simple.ParameterizedRowMapper; +import org.springframework.jdbc.core.simple.SimpleJdbcTemplate; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; +import org.springframework.transaction.annotation.Transactional; + +import javax.sql.DataSource; import java.sql.ResultSet; import java.sql.SQLException; -import org.springframework.batch.sample.domain.Game; -import org.springframework.jdbc.core.RowMapper; -import org.springframework.test.AbstractTransactionalDataSourceSpringContextTests; - /** * @author Lucas Ward * */ -public class JdbcGameDaoIntegrationTests extends AbstractTransactionalDataSourceSpringContextTests { +@RunWith(SpringJUnit4ClassRunner.class) +@ContextConfiguration(locations = {"/data-source-context.xml"}) +public class JdbcGameDaoIntegrationTests { private JdbcGameDao gameDao; private Game game = new Game(); - protected String[] getConfigLocations() { - return new String[] { "data-source-context.xml" }; + private SimpleJdbcTemplate simpleJdbcTemplate; + + @Autowired + public void setDataSource(DataSource dataSource) { + this.simpleJdbcTemplate = new SimpleJdbcTemplate(dataSource); + gameDao = new JdbcGameDao(); + gameDao.setDataSource(dataSource); + gameDao.afterPropertiesSet(); } - protected void onSetUpBeforeTransaction() throws Exception { - super.onSetUpBeforeTransaction(); - - gameDao = new JdbcGameDao(); - gameDao.setJdbcTemplate(getJdbcTemplate()); + @Before + public void onSetUpBeforeTransaction() throws Exception { game.setId("XXXXX00"); game.setYear(1996); @@ -57,20 +71,22 @@ public class JdbcGameDaoIntegrationTests extends AbstractTransactionalDataSource game.setReceptions(1); game.setReceptionYards(16); game.setTotalTd(2); + } + @Transactional @Test public void testWrite() { gameDao.write(game); - Game tempGame = (Game) getJdbcTemplate().queryForObject("SELECT * FROM GAMES where PLAYER_ID=? AND YEAR_NO=?", - new Object[] { "XXXXX00 ", new Integer(game.getYear()) }, new GameRowMapper()); + Game tempGame = simpleJdbcTemplate.queryForObject("SELECT * FROM GAMES where PLAYER_ID=? AND YEAR_NO=?", + new GameRowMapper(), "XXXXX00 ", game.getYear()); assertEquals(tempGame, game); } - public static class GameRowMapper implements RowMapper { + private static class GameRowMapper implements ParameterizedRowMapper { - public Object mapRow(ResultSet rs, int arg1) throws SQLException { + public Game mapRow(ResultSet rs, int arg1) throws SQLException { if (rs == null) { return null; diff --git a/spring-batch-samples/src/test/java/org/springframework/batch/sample/dao/JdbcJobRepositoryTests.java b/spring-batch-samples/src/test/java/org/springframework/batch/sample/dao/JdbcJobRepositoryTests.java index 8509620de..14f5fd966 100644 --- a/spring-batch-samples/src/test/java/org/springframework/batch/sample/dao/JdbcJobRepositoryTests.java +++ b/spring-batch-samples/src/test/java/org/springframework/batch/sample/dao/JdbcJobRepositoryTests.java @@ -1,5 +1,43 @@ +/* + * Copyright 2006-2008 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.dao; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import static org.junit.Assert.*; +import org.junit.Before; +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.repository.JobExecutionAlreadyRunningException; +import org.springframework.batch.core.repository.JobRepository; +import org.springframework.batch.sample.tasklet.JobSupport; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.jdbc.core.JdbcTemplate; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; +import org.springframework.test.context.transaction.AfterTransaction; +import org.springframework.transaction.PlatformTransactionManager; +import org.springframework.transaction.annotation.Transactional; +import org.springframework.transaction.support.TransactionCallback; +import org.springframework.transaction.support.TransactionTemplate; + +import javax.sql.DataSource; import java.io.Serializable; import java.sql.Timestamp; import java.util.ArrayList; @@ -8,17 +46,9 @@ import java.util.Iterator; import java.util.List; import java.util.Set; -import org.springframework.batch.core.BatchStatus; -import org.springframework.batch.core.JobExecution; -import org.springframework.batch.core.JobParameters; -import org.springframework.batch.core.repository.JobExecutionAlreadyRunningException; -import org.springframework.batch.core.repository.JobRepository; -import org.springframework.batch.sample.tasklet.JobSupport; -import org.springframework.test.AbstractTransactionalDataSourceSpringContextTests; -import org.springframework.transaction.support.TransactionCallback; -import org.springframework.transaction.support.TransactionTemplate; - -public class JdbcJobRepositoryTests extends AbstractTransactionalDataSourceSpringContextTests { +@RunWith(SpringJUnit4ClassRunner.class) +@ContextConfiguration(locations = {"/simple-job-launcher-context.xml"}) +public class JdbcJobRepositoryTests { private JobRepository repository; @@ -30,71 +60,74 @@ public class JdbcJobRepositoryTests extends AbstractTransactionalDataSourceSprin private List list = new ArrayList(); + private JdbcTemplate jdbcTemplate; + + private PlatformTransactionManager transactionManager; + + /** Logger */ + private final Log logger = LogFactory.getLog(getClass()); + + @Autowired + public void setDataSource(DataSource dataSource) { + this.jdbcTemplate = new JdbcTemplate(dataSource); + } + + @Autowired + public void setTransactionManager(PlatformTransactionManager transactionManager) { + this.transactionManager = transactionManager; + } + + @Autowired public void setRepository(JobRepository repository) { this.repository = repository; } - protected String[] getConfigLocations() { - return new String[] { "simple-job-launcher-context.xml" }; - } - - protected void onSetUpInTransaction() throws Exception { + @Before + public void onSetUpInTransaction() throws Exception { jobConfiguration = new JobSupport("test-job"); jobConfiguration.setRestartable(true); + jdbcTemplate.update("DELETE FROM BATCH_EXECUTION_CONTEXT"); + jdbcTemplate.update("DELETE FROM BATCH_STEP_EXECUTION"); + jdbcTemplate.update("DELETE FROM BATCH_JOB_EXECUTION"); + jdbcTemplate.update("DELETE FROM BATCH_JOB_PARAMS"); + jdbcTemplate.update("DELETE FROM BATCH_JOB_INSTANCE"); } - protected void onSetUpBeforeTransaction() throws Exception { - startNewTransaction(); - getJdbcTemplate().update("DELETE FROM BATCH_EXECUTION_CONTEXT"); - getJdbcTemplate().update("DELETE FROM BATCH_STEP_EXECUTION"); - getJdbcTemplate().update("DELETE FROM BATCH_JOB_EXECUTION"); - getJdbcTemplate().update("DELETE FROM BATCH_JOB_PARAMS"); - getJdbcTemplate().update("DELETE FROM BATCH_JOB_INSTANCE"); - setComplete(); - endTransaction(); - } - - protected void onTearDownAfterTransaction() throws Exception { - startNewTransaction(); + @AfterTransaction + public void onTearDownAfterTransaction() throws Exception { for (Iterator iterator = jobExecutionIds.iterator(); iterator.hasNext();) { Long id = iterator.next(); - getJdbcTemplate().update("DELETE FROM BATCH_JOB_EXECUTION where JOB_EXECUTION_ID=?", new Object[] { id }); + jdbcTemplate.update("DELETE FROM BATCH_JOB_EXECUTION where JOB_EXECUTION_ID=?", new Object[] { id }); } for (Iterator iterator = jobIds.iterator(); iterator.hasNext();) { Long id = iterator.next(); - getJdbcTemplate().update("DELETE FROM BATCH_JOB_INSTANCE where JOB_INSTANCE_ID=?", new Object[] { id }); + jdbcTemplate.update("DELETE FROM BATCH_JOB_INSTANCE where JOB_INSTANCE_ID=?", new Object[] { id }); } - setComplete(); - endTransaction(); for (Iterator iterator = jobIds.iterator(); iterator.hasNext();) { Long id = iterator.next(); - int count = getJdbcTemplate().queryForInt("SELECT COUNT(*) FROM BATCH_JOB_INSTANCE where JOB_INSTANCE_ID=?", new Object[] { id }); + int count = jdbcTemplate.queryForInt("SELECT COUNT(*) FROM BATCH_JOB_INSTANCE where JOB_INSTANCE_ID=?", new Object[] { id }); assertEquals(0, count); } } + @Transactional @Test public void testFindOrCreateJob() throws Exception { jobConfiguration.setName("foo"); - int before = getJdbcTemplate().queryForInt("SELECT COUNT(*) FROM BATCH_JOB_INSTANCE"); + int before = jdbcTemplate.queryForInt("SELECT COUNT(*) FROM BATCH_JOB_INSTANCE"); JobExecution execution = repository.createJobExecution(jobConfiguration, new JobParameters()); - setComplete(); - endTransaction(); - startNewTransaction(); - int after = getJdbcTemplate().queryForInt("SELECT COUNT(*) FROM BATCH_JOB_INSTANCE"); + int after = jdbcTemplate.queryForInt("SELECT COUNT(*) FROM BATCH_JOB_INSTANCE"); assertEquals(before + 1, after); assertNotNull(execution.getId()); } + @Transactional @Test public void testFindOrCreateJobConcurrently() throws Exception { jobConfiguration.setName("bar"); - int before = getJdbcTemplate().queryForInt("SELECT COUNT(*) FROM BATCH_JOB_INSTANCE"); + int before = jdbcTemplate.queryForInt("SELECT COUNT(*) FROM BATCH_JOB_INSTANCE"); assertEquals(0, before); - endTransaction(); - startNewTransaction(); - JobExecution execution = null; long t0 = System.currentTimeMillis(); try { @@ -112,7 +145,7 @@ public class JdbcJobRepositoryTests extends AbstractTransactionalDataSourceSprin assertNotNull(execution); - int after = getJdbcTemplate().queryForInt("SELECT COUNT(*) FROM BATCH_JOB_INSTANCE"); + int after = jdbcTemplate.queryForInt("SELECT COUNT(*) FROM BATCH_JOB_INSTANCE"); assertNotNull(execution.getId()); assertEquals(before + 1, after); @@ -120,6 +153,7 @@ public class JdbcJobRepositoryTests extends AbstractTransactionalDataSourceSprin + " - the second transaction did not block if this number is less than about 1000."); } + @Transactional @Test public void testFindOrCreateJobConcurrentlyWhenJobAlreadyExists() throws Exception { jobConfiguration.setName("spam"); @@ -129,17 +163,10 @@ public class JdbcJobRepositoryTests extends AbstractTransactionalDataSourceSprin execution.setEndTime(new Timestamp(System.currentTimeMillis())); repository.saveOrUpdate(execution); execution.setStatus(BatchStatus.FAILED); - setComplete(); - endTransaction(); - startNewTransaction(); - - int before = getJdbcTemplate().queryForInt("SELECT COUNT(*) FROM BATCH_JOB_INSTANCE"); + int before = jdbcTemplate.queryForInt("SELECT COUNT(*) FROM BATCH_JOB_INSTANCE"); assertEquals(1, before); - endTransaction(); - startNewTransaction(); - long t0 = System.currentTimeMillis(); try { doConcurrentStart(); @@ -150,7 +177,7 @@ public class JdbcJobRepositoryTests extends AbstractTransactionalDataSourceSprin } long t1 = System.currentTimeMillis(); - int after = getJdbcTemplate().queryForInt("SELECT COUNT(*) FROM BATCH_JOB_INSTANCE"); + int after = jdbcTemplate.queryForInt("SELECT COUNT(*) FROM BATCH_JOB_INSTANCE"); assertNotNull(execution.getId()); assertEquals(before, after); diff --git a/spring-batch-samples/src/test/java/org/springframework/batch/sample/dao/JdbcPlayerDaoIntegrationTests.java b/spring-batch-samples/src/test/java/org/springframework/batch/sample/dao/JdbcPlayerDaoIntegrationTests.java index e68fe889d..553921a67 100644 --- a/spring-batch-samples/src/test/java/org/springframework/batch/sample/dao/JdbcPlayerDaoIntegrationTests.java +++ b/spring-batch-samples/src/test/java/org/springframework/batch/sample/dao/JdbcPlayerDaoIntegrationTests.java @@ -1,35 +1,62 @@ -/** - * +/* + * Copyright 2006-2008 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.dao; +import static org.junit.Assert.assertEquals; import java.sql.ResultSet; import java.sql.SQLException; import org.springframework.batch.sample.domain.Player; import org.springframework.jdbc.core.RowCallbackHandler; +import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.test.AbstractTransactionalDataSourceSpringContextTests; +import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.transaction.BeforeTransaction; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.transaction.annotation.Transactional; +import org.junit.runner.RunWith; +import org.junit.Before; +import org.junit.Test; + +import javax.sql.DataSource; /** * @author Lucas Ward * */ -public class JdbcPlayerDaoIntegrationTests extends AbstractTransactionalDataSourceSpringContextTests { +@RunWith(SpringJUnit4ClassRunner.class) +@ContextConfiguration(locations = {"/data-source-context.xml"}) +public class JdbcPlayerDaoIntegrationTests { private JdbcPlayerDao playerDao; + private Player player; + private static final String GET_PLAYER = "SELECT * from PLAYERS"; - protected String[] getConfigLocations() { - return new String[] {"data-source-context.xml"}; - } + private JdbcTemplate jdbcTemplate; - protected void onSetUpBeforeTransaction() throws Exception { - super.onSetUpBeforeTransaction(); - + @Autowired + public void init(DataSource dataSource) { + + this.jdbcTemplate = new JdbcTemplate(dataSource); playerDao = new JdbcPlayerDao(); - playerDao.setJdbcTemplate(this.jdbcTemplate); - + playerDao.setJdbcTemplate(this.jdbcTemplate); + player = new Player(); player.setID("AKFJDL00"); player.setFirstName("John"); @@ -37,21 +64,23 @@ public class JdbcPlayerDaoIntegrationTests extends AbstractTransactionalDataSour player.setPosition("QB"); player.setBirthYear(1975); player.setDebutYear(1998); + } - protected void onSetUpInTransaction() throws Exception { - super.onSetUpInTransaction(); + @Before + public void onSetUpInTransaction() throws Exception { jdbcTemplate.execute("delete from PLAYERS"); } + @Transactional @Test public void testSavePlayer(){ playerDao.savePlayer(player); - getJdbcTemplate().query(GET_PLAYER, new RowCallbackHandler(){ + jdbcTemplate.query(GET_PLAYER, new RowCallbackHandler(){ public void processRow(ResultSet rs) throws SQLException { assertEquals(rs.getString("PLAYER_ID"), "AKFJDL00"); diff --git a/spring-batch-samples/src/test/java/org/springframework/batch/sample/dao/JdbcPlayerSummaryDaoIntegrationTests.java b/spring-batch-samples/src/test/java/org/springframework/batch/sample/dao/JdbcPlayerSummaryDaoIntegrationTests.java index 0418baef1..3bb9bed3b 100644 --- a/spring-batch-samples/src/test/java/org/springframework/batch/sample/dao/JdbcPlayerSummaryDaoIntegrationTests.java +++ b/spring-batch-samples/src/test/java/org/springframework/batch/sample/dao/JdbcPlayerSummaryDaoIntegrationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2006-2007 the original author or authors. + * Copyright 2006-2008 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. @@ -15,31 +15,41 @@ */ package org.springframework.batch.sample.dao; - +import static org.junit.Assert.assertEquals; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; import org.springframework.batch.sample.domain.PlayerSummary; import org.springframework.batch.sample.mapping.PlayerSummaryMapper; -import org.springframework.test.AbstractTransactionalDataSourceSpringContextTests; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.jdbc.core.JdbcTemplate; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; +import org.springframework.transaction.annotation.Transactional; + +import javax.sql.DataSource; /** * @author Lucas Ward * */ -public class JdbcPlayerSummaryDaoIntegrationTests extends - AbstractTransactionalDataSourceSpringContextTests { +@RunWith(SpringJUnit4ClassRunner.class) +@ContextConfiguration(locations = {"/data-source-context.xml"}) +public class JdbcPlayerSummaryDaoIntegrationTests { - JdbcPlayerSummaryDao playerSummaryDao; - PlayerSummary summary; + private JdbcPlayerSummaryDao playerSummaryDao; - protected String[] getConfigLocations() { - return new String[] { "data-source-context.xml" }; - } + private PlayerSummary summary; - protected void onSetUpBeforeTransaction() throws Exception { - super.onSetUpBeforeTransaction(); + private JdbcTemplate jdbcTemplate; + @Autowired + public void init(DataSource dataSource) { + + this.jdbcTemplate = new JdbcTemplate(dataSource); playerSummaryDao = new JdbcPlayerSummaryDao(); - playerSummaryDao.setJdbcTemplate(getJdbcTemplate()); + playerSummaryDao.setJdbcTemplate(this.jdbcTemplate); summary = new PlayerSummary(); summary.setId("AikmTr00"); @@ -54,21 +64,22 @@ public class JdbcPlayerSummaryDaoIntegrationTests extends summary.setReceptions(0); summary.setReceptionYards(0); summary.setTotalTd(0); + } - protected void onSetUpInTransaction() throws Exception { - super.onSetUpInTransaction(); + @Before + public void onSetUpInTransaction() throws Exception { jdbcTemplate.execute("delete from PLAYER_SUMMARY"); } + @Transactional @Test public void testWrite() { playerSummaryDao.write(summary); - PlayerSummary testSummary = (PlayerSummary) getJdbcTemplate() - .queryForObject("SELECT * FROM PLAYER_SUMMARY", + PlayerSummary testSummary = (PlayerSummary) jdbcTemplate.queryForObject("SELECT * FROM PLAYER_SUMMARY", new PlayerSummaryMapper()); assertEquals(testSummary, summary); diff --git a/spring-batch-samples/src/test/java/org/springframework/batch/sample/dao/JdbcTradeWriterTests.java b/spring-batch-samples/src/test/java/org/springframework/batch/sample/dao/JdbcTradeWriterTests.java index 15c99667b..67ae9ca0e 100644 --- a/spring-batch-samples/src/test/java/org/springframework/batch/sample/dao/JdbcTradeWriterTests.java +++ b/spring-batch-samples/src/test/java/org/springframework/batch/sample/dao/JdbcTradeWriterTests.java @@ -1,25 +1,62 @@ +/* + * Copyright 2006-2008 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.dao; +import static org.junit.Assert.assertEquals; import java.math.BigDecimal; import java.sql.ResultSet; import java.sql.SQLException; import org.springframework.batch.sample.domain.Trade; import org.springframework.jdbc.core.RowCallbackHandler; +import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.jdbc.support.incrementer.AbstractDataFieldMaxValueIncrementer; import org.springframework.test.AbstractTransactionalDataSourceSpringContextTests; +import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.transaction.annotation.Transactional; +import org.junit.runner.RunWith; +import org.junit.Test; -public class JdbcTradeWriterTests extends AbstractTransactionalDataSourceSpringContextTests { +import javax.sql.DataSource; - protected String[] getConfigLocations() { - return new String[] { "data-source-context.xml" }; +@RunWith(SpringJUnit4ClassRunner.class) +@ContextConfiguration(locations = {"/data-source-context.xml"}) +public class JdbcTradeWriterTests { + + private JdbcTemplate jdbcTemplate; + + private AbstractDataFieldMaxValueIncrementer incrementer; + + @Autowired + public void setDataSource(DataSource dataSource) { + this.jdbcTemplate = new JdbcTemplate(dataSource); } + @Autowired + public void setIncrementer(AbstractDataFieldMaxValueIncrementer incrementer) { + this.incrementer = incrementer; + } + + @Transactional @Test public void testWrite() { JdbcTradeDao writer = new JdbcTradeDao(); - AbstractDataFieldMaxValueIncrementer incrementer = (AbstractDataFieldMaxValueIncrementer)applicationContext.getBean("incrementerParent"); incrementer.setIncrementerName("TRADE_SEQ"); writer.setIncrementer(incrementer); diff --git a/spring-batch-samples/src/test/java/org/springframework/batch/sample/dao/OrderTransformerTests.java b/spring-batch-samples/src/test/java/org/springframework/batch/sample/dao/OrderTransformerTests.java index 07b3fb887..51283aac5 100644 --- a/spring-batch-samples/src/test/java/org/springframework/batch/sample/dao/OrderTransformerTests.java +++ b/spring-batch-samples/src/test/java/org/springframework/batch/sample/dao/OrderTransformerTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2006-2007 the original author or authors. + * Copyright 2006-2008 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. @@ -15,6 +15,9 @@ */ package org.springframework.batch.sample.dao; +import static org.junit.Assert.assertTrue; +import org.junit.Test; + import java.math.BigDecimal; import java.util.ArrayList; import java.util.Collection; @@ -35,10 +38,11 @@ import org.springframework.batch.sample.domain.Order; * @author Dave Syer * */ -public class OrderTransformerTests extends TestCase { +public class OrderTransformerTests { private OrderTransformer converter = new OrderTransformer(); + @Test public void testConvert() throws Exception { converter.setAggregators(new HashMap() { { diff --git a/spring-batch-samples/src/test/java/org/springframework/batch/sample/item/writer/CustomerUpdateProcessorTests.java b/spring-batch-samples/src/test/java/org/springframework/batch/sample/item/writer/CustomerUpdateProcessorTests.java index 5e802c051..0bfda2eb8 100644 --- a/spring-batch-samples/src/test/java/org/springframework/batch/sample/item/writer/CustomerUpdateProcessorTests.java +++ b/spring-batch-samples/src/test/java/org/springframework/batch/sample/item/writer/CustomerUpdateProcessorTests.java @@ -5,6 +5,7 @@ import java.math.BigDecimal; import junit.framework.TestCase; import org.springframework.batch.sample.dao.JdbcCustomerDebitDao; +import org.springframework.batch.sample.dao.CustomerDebitDao; import org.springframework.batch.sample.domain.CustomerDebit; import org.springframework.batch.sample.domain.Trade; import org.springframework.batch.sample.item.writer.CustomerUpdateWriter; @@ -19,7 +20,7 @@ public class CustomerUpdateProcessorTests extends TestCase { trade.setPrice(new BigDecimal(123.0)); //create dao - JdbcCustomerDebitDao dao = new JdbcCustomerDebitDao() { + CustomerDebitDao dao = new CustomerDebitDao() { public void write(CustomerDebit customerDebit) { assertEquals("testCustomerName", customerDebit.getName()); assertEquals(new BigDecimal(123.0), customerDebit.getDebit()); diff --git a/spring-batch-samples/src/test/resources/org/springframework/batch/sample/dao/JdbcCustomerDebitDaoTests-context.xml b/spring-batch-samples/src/test/resources/org/springframework/batch/sample/dao/JdbcCustomerDebitDaoTests-context.xml new file mode 100644 index 000000000..0f0aa9908 --- /dev/null +++ b/spring-batch-samples/src/test/resources/org/springframework/batch/sample/dao/JdbcCustomerDebitDaoTests-context.xml @@ -0,0 +1,11 @@ + + + + + + + + \ No newline at end of file