需要的jar包
<dependency> <groupId>org.springframework</groupId> <artifactId>spring-test</artifactId> <version>3.2.3.RELEASE</version> <scope>test</scope> </dependency> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.11</version> <scope>test</scope> </dependency>
测试类
package firstMybatisPlugin; import java.math.BigDecimal; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import org.springframework.transaction.annotation.Transactional; import cn.zno.pojo.Person; import cn.zno.service.PersonService; @ContextConfiguration(locations = {"classpath:beans-transaction.xml"}) @RunWith(SpringJUnit4ClassRunner.class) @Transactional public class TestPerson { @Autowired private PersonService personService; @Test public void insert(){ Person person = new Person(); person.setName("xiaoming"); person.setAge(BigDecimal.valueOf(11)); } }
1. 运行这个测试类会加载"classpath:beans-transaction.xml" 配置文件,如果有多个{"",""}
2. 由SpringJUnit4ClassRunner.class 运行
3. 开启事务(自动回滚,不会对数据库造成影响)
补充:
1.自动注入@Autowired需要开启 <context:annotation-config />
2. 如果不是在 beans.xml 中配置bean,则需要开启扫描
<context:component-scan base-package="cn.zno" />
并在类加注解 @Component 或者 @Service 之类的,以确保这个bean在bean工厂中。