前提:
导入junit-4.12.jar和hamcrest-all-1.3.jar
hamcrest-all-1.3.jarjunit-4.12.jar
创建文件:
1.创建JunitTest类
2.创建model类
3.创建applicationContext.xml
代码:
model.java
package com.how2java.bean;
import org.springframework.stereotype.Repository;
@Repository
public class model {
private String modelID;
public String getModelID() {
return modelID;
}
public void setModelID(String modelID) {
this.modelID = modelID;
}
}
applicationContext.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"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:p="http://www.springframework.org/schema/p"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop.xsd">
<bean id="model" name="model" class="com.how2java.bean.model">
<property name="modelID" value="This is a modelID"/>
</bean>
<bean id="model2" name="model2" class="com.how2java.bean.model">
<property name="modelID" value="This is a modelID2"/>
</bean>
</beans>
JunitTest.java
package com.how2java.test;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import com.how2java.bean.model;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:applicationContext.xml")
public class JunitTest {
@Autowired()
@Qualifier("model")
model c;
@Test
public void test(){
System.out.println(c.getModelID());
}
}
要点:
1.@Autowired是根据类型匹配,如果有多个匹配的,需要配合@Qualifier来匹配名称。如果有多个匹配的,且没有写@Qualifier,会报错。
2.@RunWith,表示这是一个Spring的测试类。
3. @ContextConfiguration(“classpath:applicationContext.xml”),定位Spring的配置文件。
4.@Test,测试逻辑。