@Configuration @ComponentScan(basePackages = "lx.spring.core") @PropertySource("classpath:prod.properties") @EnableTransactionManagement public class AppConfig {
@Repository @Profile("test") public class JdbcAccountRepository implements AccountRepository {
private JdbcTemplate template; private static long nextId = 4;
@Autowired public JdbcAccountRepository(DataSource dataSource) { template = new JdbcTemplate(dataSource); }
@Override public List<Account> getAccounts() { String sqlText = "SELECT * FROM account"; return template.query(sqlText, new AccountMapper()); }
@Override public Account getAccount(Long id) { String sqlText = "SELECT * FROM account WHERE id=?"; return template.queryForObject(sqlText, new AccountMapper(), id); }
@Override public int getNumberOfCounts() { String sqlText = "SELECT count(*) FROM account"; return template.queryForObject(sqlText, Integer.class); }
@Override public Long createAccount(BigDecimal initialBalance) { String sqlText = "insert into account(id, balance) values(?, ?)"; long id = nextId ++; int uc = template.update(sqlText, id, initialBalance); return id; }
@Override public int deleteAccount(Long id) { String sqlText = "delete from account where id=?"; return template.update(sqlText, id); }
@Override public void updateAccount(Account account) { String sqlText = "update account set balance=? where id = ?"; template.update(sqlText, account.getBalance(), account.getId()); }
private class AccountMapper implements RowMapper<Account>{ @Override public Account mapRow(ResultSet rs, int rowNum) throws SQLException { return new Account(rs.getLong("id"), rs.getBigDecimal("balance")); } } }
@RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(classes = AppConfig.class) @Transactional @ActiveProfiles("test") public class JdbcAccountRepositoryTest {
@RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(classes = AppConfig.class) @Transactional @ActiveProfiles("test") public class AccountServiceTest {
@Autowired private AccountService service;
@Test public void deposit() throws Exception { BigDecimal start = service.getBalance(1L); BigDecimal amount = new BigDecimal("50.0");
assertThat(acct1finish, is(closeTo(service.getBalance(1L), new BigDecimal("0.01")))); assertThat(acct2finish, is(closeTo(service.getBalance(2L), new BigDecimal("0.01")))); } }