1. 程式人生 > >單元測試啟動spring容器

單元測試啟動spring容器

介紹在spring的框架下,做單元測試的兩種辦法。

    一、使用spring中對Junit框架的整合功能

    除了junit4和spring的jar包,還需要spring-test.jar。引入如下依賴:

<dependency>
			<groupId>junit</groupId>
			<artifactId>junit</artifactId>
			<version>4.4</version>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-test</artifactId>
			<version>2.5</version>
		</dependency>
<dependency>
	<groupId>org.springframework</groupId>
  	<artifactId>spring-test</artifactId>
  	<version>3.1.1.RELEASE</version>
</dependency>

    @ContextConfiguration需要配上spring的配置檔案,這樣就可以在測試類中使用註解簡單的注入需要的bean了。簡單高效。

@RunWith(SpringJUnit4ClassRunner.class)  
@ContextConfiguration(locations ={"/applicationContext.xml"})  
public class ProducerConsumerTest {
 
    @Autowired
    private Sender sender;
    @Autowired
    @Qualifier("queueDestination")
    private Destination destination;
    
   @Test
    public void testSend() {
        for (int i=0; i<2; i++) {
         sender.sendInfo(destination, "你好,生產者!這是訊息:" + (i+1));
        }
    }
    
}
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration({"classpath:applicationContext.xml"})
public class ReadDaoImplTest {
	@Resource ReadDao readDao;
	
	@Test
	public void getListTest(){
		List<Client> clientList = readDao.getList("client.test", null);
		
		for(Client c:clientList){
			System.out.println(c.getVersionNum());
		}
	}
}

    二、手動載入spring的配置檔案,並啟動spring容器

public class ReadDaoImplTest {
	
	public  static void main(String[] args){
		ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");

		context.start();

		ReadDao fqaService = (ReadDao) context.getBean("readDao");
		System.out.println(fqaService);
	}
	
}
public class ReadDaoImplTest {
	
	public  static void main(String[] args){
		ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");

		context.start();

		ReadDao fqaService = (ReadDao) context.getBean("readDao");
		System.out.println(fqaService);
	}
	
}

    執行這兩種測試方法,EclipseIDE下都只需要Ctrl+F11。