Mockito是mocking框架,它讓你用簡潔的API作測試。並且Mockito簡單易學,它可讀性強和驗證語法簡潔。
注:因爲項目中只須要註解,就直接用註解來mock對象框架
@RunWith(MockitoJUnitRunner.class) public class MockitoExample2 { @Mock private List mockList; @Test public void shorthand(){ mockList.add(1); Mockito.verify(mockList).add(1); } }
public class MockitoExample2 { @Mock private List mockList; public MockitoExample2(){ MockitoAnnotations.initMocks(this); } @Test public void shorthand(){ mockList.add(1); Mockito.verify(mockList).add(1); } }
Mockito提供vertify關鍵字來實現校驗方法是否被調用
注:兩種方式都是經過的,看我的喜愛測試
mock出的對象永遠是假的對象,全部的方法和變量都被置空。this
@RunWith(MockitoJUnitRunner.class) public class MockDemoTest { @Mock private List mockList; @Test public void shorthand(){ mockList.add(1); System.out.println(mockList); Mockito.verify(mockList).add(1); }