1.概述
Spring 提供了单元测试的强大支持,主要特性包括:
- 支持主流的测试框架 Junit 和 TestNG
- 支持在测试类中使用依赖注入 Denpendency Injection
- 支持测试类的自动化事务管理
- 支持使用各种注释标签,提高开发效率和代码简洁性
- Spring 3.1 更是支持在测试类中使用非 XML 配置方法和基于 Profile 的 bean 配置模式
下面提供一个Spring基于junit的测试用例,数据操作使用Spring data jpa ,因为以前刚好配置过,就拿过来用。
2.具体实现
实体类:User ,简单的Java bean ,就不贴了
dao:
public interface UserDao extends CrudRepository<User, Long>{
Page<User> findAll(Pageable pageable);
User findById(long id);
User findByName(String name);
User findByLoginName(String loginName);
}
解释:使用data jpa 提供的借口CrudRepository,此接口提供基本的增删改查操作。
Service类
@Service
public class AccountService implements IAccoutService{
@Autowired
private UserDao userDao;
@Transactional
public void saveUser(User user){
userDao.save(user);
}
public List<User> findUserByPage(int page){
Pageable pageable = new PageRequest(page, 10);
Page<User> page1 = userDao.findAll(pageable);
return page1.getContent() ;
}
public User findUserById(long id){
return userDao.findById(id);
}
public User findUserByLoginName(String name){
return userDao.findByLoginName(name);
}
Logger logger = LoggerFactory.getLogger(AccountService.class);
}
配置文件:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:jdbc="http://www.springframework.org/schema/jdbc" xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:jpa="http://www.springframework.org/schema/data/jpa"
xsi:schemaLocation="
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.2.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.2.xsd
http://www.springframework.org/schema/jdbc http://www.springframework.org/schema/jdbc/spring-jdbc-3.2.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.2.xsd
http://www.springframework.org/schema/data/jpa http://www.springframework.org/schema/data/jpa/spring-jpa-1.3.xsd"
default-lazy-init="true">
<description>Spring公共配置</description>
<!-- 读配置数据 -->
<context:property-placeholder
ignore-resource-not-found="true" location="classpath*:/application.properties" />
<!-- 注解支持 -->
<context:annotation-config />
<!-- 使用annotation 自动注册bean,并检查@Required,@Autowired的属性已被注入 -->
<context:component-scan base-package="com.blueinfo.jee">
<context:exclude-filter type="annotation"
expression="org.springframework.stereotype.Controller" />
<context:exclude-filter type="annotation"
expression="org.springframework.web.bind.annotation.ControllerAdvice" />
</context:component-scan>
<!-- Jpa Entity Manager 配置 -->
<bean id="entityManagerFactory"
class="org.springframework.orm.jpa.LocalConta