http://412887952-qq-com.iteye.com/blog/2317832-Junit1.4版本
添加依賴
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
測試Service
@Service
public class StudentService{
@Resource
private StudentDao studentDao;
public String junitTest(){
return "hello";
}
}
測試
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.SpringApplicationConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.web.WebAppConfiguration;
import com.tutorial.springboot.AppStart;
import com.tutorial.springboot.service.StudentService;
//SpringJUnit支持,由此引入Spring-Test框架支持
@RunWith(SpringJUnit4ClassRunner.class)
//指定我們SpringBoot工程的Application啟動類
@SpringApplicationConfiguration(classes = AppStart.class)
//1.4.0已經被標注過時,需要替換為@SpringbootTest注解
//由于是Web項目,Junit需要模擬ServletContext,因此我們需要給我們的測試類加上@WebAppConfiguration
@WebAppConfiguration
public class SpringBootTest{
@Resource
private StudentService studentService;
@Test
public void testGetName(){
Assert.assertEquals("hello",studentService.junitTest());
}
}
Junit基本注解介紹
//在所有測試方法前執(zhí)行一次,一般在其中寫上整體初始化的代碼 @BeforeClass
//在所有測試方法后執(zhí)行一次,一般在其中寫上銷毀和釋放資源的代碼 @AfterClass
//在每個測試方法前執(zhí)行,一般用來初始化方法(比如我們在測試別的方法時,類中與其他測試方法共享的值已經被改變,為了保證測試結果的有效性,我們會在@Before注解的方法中重置數據) @Before
//在每個測試方法后執(zhí)行,在方法執(zhí)行完成后要做的事情 @After
// 測試方法執(zhí)行超過1000毫秒后算超時,測試將失敗 @Test(timeout = 1000)
// 測試方法期望得到的異常類,如果方法執(zhí)行沒有拋出指定的異常,則測試失敗 @Test(expected = Exception.class)
// 執(zhí)行測試時將忽略掉此方法,如果用于修飾類,則忽略整個類 @Ignore(“not ready yet”) @Test
@RunWith 在JUnit中有很多個Runner,他們負責調用你的測試代碼,每一個Runner都有各自的特殊功能,你要根據需要選擇不同的Runner來運行你的測試代碼。 如果我們只是簡單的做普通Java測試,不涉及SpringWeb項目,你可以省略@RunWith注解,這樣系統(tǒng)會自動使用默認Runner來運行你的代碼。