單元測試(Junit)使用及Junit支援Spring IOC的依賴注入
阿新 • • 發佈:2018-12-09
單元測試在我們日常寫程式碼的過程中特別重要,可以儘快發現區域性的程式碼問題
Junit是我經常使用的一種單元測試工具
下面先寫一個單元測試的示例 先寫一個提供呼叫方法的類
package test;
/**
* @author coder
* @version v0.1
* @create 2018-09-11 14:12
**/
public class DemoService {
public String demo1(){
return "Hello Coder!";
}
}
比如我們在JunitDemo類中的junitDemo呼叫了上面的類中的demo1方法並進行一些業務處理,然後想看一下呼叫的結果,有沒有報錯,這樣就可以使用單元測試來進行測試(在接觸單元測試以前,我基本上都是使用main方法來測試的,但是一個類只能有一個main方法,如果要測試的比較多就會導致測試程式碼特別混亂),執行單元測試的方法和執行main方法類似,滑鼠放在方法體裡,右鍵,run即可。
package test; import org.junit.Test; /** * Junit演示單元測試 * * @author coder * @version v0.1 * @create 2018-09-11 14:12 **/ public class JunitDemo { @Test public void junitDemo(){ DemoService demoService= new DemoService(); System.out.println(demoService.demo1()+"123654789"); } }
進行單元測試的方法必須是無返回值的,也就是void的,不然會報如下異常
正常執行輸出結果如下:
現在的Java專案spring框架的應用非常的普遍,我們在遇到spring進行依賴注入的時候,這樣進行單元測試就需要在類名上加上如下兩行註解才行
@RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(locations = {"classpath*:/applicationContext.xml"}) 第二行的註解是載入spring配置檔案的,這個根據你的配置檔案的位置和檔名進行修改
package test; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; /** * Junit演示單元測試 * * @author coder * @version v0.1 * @create 2018-09-11 14:12 **/ @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(locations = {"classpath*:/applicationContext.xml"}) public class JunitDemo { @Autowired DemoService demoService1; @Test public void junitDemo(){ DemoService demoService= new DemoService(); System.out.println(demoService.demo1()+"123654789"); } @Test public void junitDemo1(){ System.out.println(demoService1.demo1()+"spring 依賴注入"); } }
執行junitDemo1的單元測試的結果如下圖所示: