org.springframework spring-test
需要的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工厂中。
方式二
add by zxg 20210926
src/main/resources/aa.xml
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd"> <bean id="foo" class="cn.xs.wo.Foo"></bean> </beans>
package cn.xs.wo; import org.junit.Test; import org.springframework.context.support.GenericXmlApplicationContext; public class FooApplicationTest { @Test public void test() { GenericXmlApplicationContext ac = new GenericXmlApplicationContext("aa.xml"); Foo foo = ac.getBean(Foo.class); assert(foo != null); ac.close(); } }
日志:
15:33:18.584 [main] DEBUG org.springframework.beans.factory.xml.XmlBeanDefinitionReader - Loaded 1 bean definitions from class path resource [aa.xml] 15:33:18.586 [main] DEBUG org.springframework.context.support.GenericXmlApplicationContext - Refreshing org.springframework.context.support.GenericXmlApplicationContext@6833ce2c 15:33:18.634 [main] DEBUG org.springframework.beans.factory.support.DefaultListableBeanFactory - Creating shared instance of singleton bean 'foo' 15:33:18.758 [main] DEBUG org.springframework.context.support.GenericXmlApplicationContext - Closing org.springframework.context.support.GenericXmlApplicationContext@6833ce2c, started on Sun Sep 26 15:33:18 CST 2021