一、整合Junit的步骤
1.在pom.xml配置文件中添加Junit的坐标
org.springframework
spring-test
5.0.2.RELEASE
2.修改pom.xml配置文件中Junit的坐标版本为4.12及以上
junit
junit
4.12
3.将测试类中定义的业务层实现类对象添加注解 @Autowired,使其按照类型,将spring中唯一的该类型的bean对象注入
public class XXXServiceTest {
@Autowired
private IXXXService as = null;
}
4.在本项目的Spring配置类(有@import或@Configuration注解)中添加以下注解
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = spring配置类.class)
public class XXXServiceTest {
@Autowired
private IXXXService as = null;
}
二、项目搭建
1.项目整体框架
2.持久层接口
package com.huhai.dao;
import com.huhai.domain.Account;
import java.util.List;
/**
* 账户的持久层接口
*/
public interface IAccountDao {
/**
* 查询所有
* @return
*/
List findAllAccount();
/**
* 查询一个
* @return
*/
Account findAccountById(Integer accountId);
/**
* 保存
* @param account
*/
void saveAccount(Account account);
/**
* 更新
* @param account
*/
void updateAccount(Account account);
/**
* 删除
* @param acccountId
*/
void deleteAccount(Integer acccountId);
}
3.持久层接口实现类
package com.huhai.dao.impl;
import com.huhai.dao.IAccountDao;
import com.huhai.domain.Account;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import java.util.List;
/**
* 账户的持久层实现类
*/
@Repository("accountDao")
public class AccountDaoImpl implements IAccountDao {
@Autowired
private QueryRunner runner;
public List findAllAccount() {
try{
return runner.query("select * from account",new BeanListHandler(Account.class));
}catch (Exception e) {
throw new RuntimeException(e);
}
}
public Account findAccountById(Integer accountId) {
try{
return runner.query("select * from account where id = ? ",new BeanHandler(Account.class),accountId);
}catch (Exception e) {
throw new RuntimeException(e);