1. 程式人生 > >Spring中的測試

Spring中的測試

Spring中的測試

需要注意的是:

 

 

具體檔案格式

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"

xsi:schemaLocation ="

http://www.springframework.org/schema/beans

http://www.springframework.org/schema/beans/spring-beans.xsd" >

<import resource="classpath:testworld/test-context.xml"></import>

</beans>

 

 

world類

package testworld;

 

public class world {

public world(){

System.out.println("所謂的焦慮就是書讀得太少,而想得又太多");

}

public void sayhello(){

System.out.println("世界,你好");

}

}

 

 

test測試類

package testworld;

 

import org.junit.Test;

import org.junit.runner.RunWith;

import org.springframework.beans.factory.BeanFactory;

import org.springframework.beans.factory.annotation.Autowired

;

import org.springframework.beans.factory.xml.XmlBeanFactory;

import org.springframework.core.io.ClassPathResource;

import org.springframework.core.io.Resource;

import org.springframework.test.context.ContextConfiguration;

import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

//SpringJUnit4ClassRunner.class為單元測試

@RunWith(SpringJUnit4ClassRunner.class)

//@ContextConfiguration:關聯自己的測試檔案,xml格式檔案

////第一種設定方式

//@ContextConfiguration("classpath:testworld/world.xml")

//第二種設定方式

@ContextConfiguration

 

 

public class test {

@Test

public void test(){

//第一步獲取資原始檔classpath路徑

Resource resource=new ClassPathResource("applicationContext.xml");

//第二步,根據資原始檔建立spring容器

BeanFactory factory=new XmlBeanFactory(resource);

//建立物件

world wo=factory.getBean(world.class);

wo.sayhello();

}

//演示spring的測試

// @Autowired:自動把spring容器中的bean物件設定到wo,並且根據物件的型別來尋找到的

@Autowired

private world wo;

@Test

public void testbean(){

wo.sayhello();

}

}

 

 

test-context.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/beanshttp://www.springframework.org/schema/beans/spring-beans.xsd" >

<bean id="hello" class="testworld.world"></bean>

</beans>

 

 

測試結果: