1. 程式人生 > >springMVC 整合mockito單元測試學習

springMVC 整合mockito單元測試學習

之前一直在一個誤區裡。徘徊了一兩天;因為看了好多mockito網站,都沒找到關於mockito用法根本作用。都比較書面化。所以在這裡希望能寫的簡單點對於初學者,而且對這方面經驗弱的學者們!

首先,mockito是一般結合junit測試框架一起使用的。他們區別也很明顯,mockito主要是用於模擬測試,mock模擬外部依賴,根據自己的期望,設定等操作實現,來判斷程式碼邏輯,引數等是否正確,如果,測試編譯不通過,說明不通過。這裡不會跟資料庫之類的打交道。比如存一個數據,編譯通過資料庫不會多出一條資料。所以這就是跟junit的區別。他只是模擬程式碼測試。Mock用來判斷測試通過還是失敗。

Mockito

是一套非常強大的測試框架,被廣泛的應用於Java程式的unit test中,而在其中被使用頻率最高的恐怕要數"Mockito.when(...).thenReturn(...)"了。那這個用起來非常便捷的"Mockito.when(...).thenReturn(...)",其背後的實現原理究竟為何呢?為了一探究竟,筆者實現了一個簡單的MyMockito,也提供了類似的"MyMockito.when(...).thenReturn(...)"支援。當然這個實現只是一個簡單的原型,完備性和健壯性上都肯定遠遠不及mockito(比如沒有annotation支援和thread safe),但應該足以幫助大家理解"Mockito.when(...).thenReturn(...)"的核心實現原理。

至於,關於mockito的介紹和原理,大家可以看官網,http://blog.csdn.net/bboyfeiyu/article/details/52127551點選開啟連結

用法案例講解網址,點選開啟連結http://www.cnblogs.com/Ming8006/p/6297333.html

接下來,進行案例開發

pom.xml

<!-- test -->
<dependency>
    <groupId>junit</groupId>
    <artifactId>junit</artifactId>
    <version>${junit.version}</version>
    <scope>test</scope>
</dependency>
<!-- mockito -->
<dependency>
    <groupId>org.mockito</groupId>
    <artifactId>mockito-all</artifactId>
    <version>${mockito.version}</version>
    <scope>test</scope>
</dependency>

測試類:

@RunWith(SpringJUnit4ClassRunner.class)// 整合Spring-Test與JUnit
//@ContextConfiguration(locations = {"classpath*:spring/spring-context.xml"})
@ContextConfiguration(locations ="classpath*:/spring/spring-context.xml")// 載入需要的配置配置
@Transactional          //事務回滾,便於重複測試 ext
public class EnterpriseInfoServiceTest extends BaseTest {
    @Autowired
    @InjectMocks//@InjectMocks用於標識被測物件,從而把由@mock表示的依賴物件自動注入到被測物件中
    protected EnterpriseInfoService enterpriseInfoService;//測試的類(serviceImpl)
    @Mock//@Mock用於表示依賴物件
    private EnterpriseInfoMapper mapper;//依賴的類(dao)
    @Before
    public void setUp() {//可以在每一次單元測試前準備執行一些東西
        MockitoAnnotations.initMocks(this);
    }
   
    @Test
    public void deletes() {

        String[] str = {"123","124","125"};
       // enterpriseInfoService.deleteByKeys(str);
        boolean falg = enterpriseInfoService.deleteByKeys(str);
Assert.assertTrue(falg );//驗證返回的結果是不是正確的

}

 @Test  
  public void update(){ 
       EnterpriseInfo enterpriseInfo = new EnterpriseInfo(); 
       enterpriseInfo.setEntNum("123");
        enterpriseInfo.setEntNameCn("中安");
        enterpriseInfo.setEntType("1"); 
       enterpriseInfo.setRecordFlag(2);
        enterpriseInfoService.update(enterpriseInfo);  
      verify(mapper, times(1)).update(enterpriseInfo);  //針對返回值為void方法的驗證
      //或       
     //  doThrow(new RuntimeException()).when(mapper).update(enterpriseInfo);         }

這是關於mockito所有用法的demo點選開啟連結http://pan.baidu.com/s/1o8SF9qE