Spring 測試
- 測試是開發工作中不可或缺的部分。
- 單元測試隻針對目前開發的類和方法進行測試,可以簡單通過模拟依賴來實作,對運作環境沒有依賴。
- 但是單元測試隻能驗證目前類或方法是否正常工作,而我們想要知道系統的各個部分組合在一起是否能正常工作,這就是內建測試存在的意義。
- 內建測試為我們提供了一種無須部署或運作程式來完成驗證系統各部分是否正常協同工作的能力。
Spring TestContext FrameWork
Spring
通過
TestContext FrameWork
對內建測試提供頂級支援。它不依賴于特定的測試架構。支援Junit也支援TestNG
簡單示例
1,在pom.xml中添加Spring測試的依賴包
<!--07_新的依賴:使用Spring提供的內建測試-->
<dependency>
<groupId>${spring-groupId}</groupId>
<artifactId>spring-test</artifactId>
<version>${spring-framework.version}</version>
</dependency>
2,建立目标Bean
package com.zyf;
import org.springframework.stereotype.Service;
/**
* Created by zyf on 2018/3/5.
*/
@Service
public class TargetService {
private String content;
public TargetService(String content) {
this.content = content;
}
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
}
3,建立配置類
package com.zyf;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Profile;
/**
* Created by zyf on 2018/3/5.
*/
@Configuration
public class TestConfig {
@Bean
@Profile("dev")
public TargetService devTargetService(){
//開發環境
return new TargetService("for development profile");
}
@Bean
@Profile("prod")
public TargetService prodTargetService(){
//生産環境
return new TargetService("for production profile");
}
}
4,在test/java/com.zyf下建立測試類
package com.zyf;
import org.junit.Assert;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ActiveProfiles;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
/**
* Created by zyf on 2018/3/5.
*/
@RunWith(SpringJUnit4ClassRunner.class)
//在junit環境下提供Spring TestContext Framework的功能
@ContextConfiguration(classes = {TestConfig.class})
//加載配置ApplicationContext,classes參數用來加載配置類
@ActiveProfiles("prod")//聲明目前正在活動的profile(可以了解為環境)
public class Test {
@Autowired//注入
private TargetService targetService;
@org.junit.Test
public void prodBeanShouldInject(){
String expected = "for production profile";
String actual = targetService.getContent();
//判斷二者是否相等
Assert.assertEquals(expected,actual);
}
}