Junit4测试Spring注入

来源:互联网 发布:ios程序员就业 编辑:程序博客网 时间:2024/05/10 21:27

1、使用的jar

    spring.jar

   org.springframework.test-3.0.5.RELEASE.jar

  //junit4测试所需jar

   Junit.jar

  org.hamcrest.core_1.1.0.v20090501071000.jar

2、注解

在类上的配置Annotation 
@RunWith(SpringJUnit4ClassRunner.class)用于配置spring中测试的环境 
@ContextConfiguration(Locations="classpath:application.xml")用于指定配置文件所在的位置 
@Test标注在方法前,表示其是一个测试的方法无需在其配置文件中额外设置属性. 

3、实例

importorg.apache.log4j.Logger;
import org.junit.Test;
import org.junit.runner.RunWith;
importorg.springframework.beans.factory.annotation.Autowired;
importorg.springframework.beans.factory.annotation.Qualifier;
import org.springframework.test.context.ContextConfiguration;
importorg.springframework.test.context.junit4.SpringJUnit4ClassRunner;

importcom.ins.service.Person;

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations ="classpath:applicationContext.xml")
public class PersonTest extends TestInit {
 
 public static final Logger LOG= Logger.getLogger(PersonTest.class);
 
 @Autowired
 @Qualifier("chinese")//注释一个字段或参数,当自动绑定时它作为候选bean的限定器。它也可以用于自定义的限定器注释
 private Person person;
 
 @Test
 public void testChinese(){
  LOG.info("-------------- starttestChinese()---------");
  //Person person=(Person)context.getBean("chinese");
  System.out.println(person.sayHello("张三"));
  System.out.println(person.sayGoodBye("王三"));
  LOG.info("--------------- endtestChinese()------------");
 }
 
 @Test
 public void testAmerical(){
  LOG.info(" ------------starttestAmerical()----------");
  //Person person=(Person)context.getBean("america");
  System.out.println(person.sayHello("张五"));
  System.out.println(person.sayGoodBye("王五"));
  LOG.info(" -------------endtestAmerical()--------");
 }

 publicPerson getPerson() {
  return person;
 }

 publicvoid setPerson(Person person) {
  this.person = person;
 }
 
 

}


  

 

 

0 0
原创粉丝点击