84334595 2019-06-28
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出的对象永远是假的对象,所有的方法和变量都被置空。
@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); }