The
TestContext
framework, first released with Spring 2.5 provides
comprehensive support for system testing using the JUnit and TestNG testing frameworks.
JavaConfig provides integration with the TestContext framework via
JavaConfigContextLoader
.
package com.bank; /** * Configures the TransferService application */ @Configuration public class TransferAppConfig { @Bean public TransferService transferService() { return new TransferServiceImpl(accountRepository()); } @Bean public AccountRepository accountRepository() { return new JdbcAccountRepository(dataSource()); } @Bean public DataSource dataSource() { // create and return a new DataSource } }
/** * System tests for the TransferService application */ @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(locations="com.bank.TransferAppConfig", loader=JavaConfigContextLoader.class) public class TransferServiceTests { // autowire in the beans to test from the TransferServiceApp application context @Autowired TransferService transferService; SimpleJdbcTemplate jdbcTemplate; // DataSource parameter gets autowired from the TransferServiceApp context @Autowired void initJdbcTemplate(DataSource dataSource) { this.jdbcTemplate = new SimpleJdbcTemplate(dataSource); } @Test public void testTransferFunds() { String balQuery = "select balance from accounts where id=?"; // execute assertions against the jdbcTemplate that // prove initial conditions are correct assertThat(jdbcTemplate.queryForObject(balQuery, double.class, "2", equalTo(100.00d); // transfer 300 dollars from account with id 1 to account with id 2 transferService.transfer(300.00d, "1", "2"); // execute assertions against the jdbcTemplate that // the database has been updated properly. assertThat(jdbcTemplate.queryForObject(balQuery, double.class, "2", equalTo(400.00d); } // additional @Test methods... }
Note | |
---|---|
Unfortunately, due to compatibility constraints with the TestContext framework's
@ContextConfiguration annotation, the fully-qualified classname for
com.bank.TransferAppConfig must be expressed as a string. This has
a negative effect on refactorability, and will be improved in the future if possible.
Vote for SJC-238
if this improvement is important to you.
|