mockit测试

 //静态导入mockit包
 import static org.mockito.Mockito.*;

 //创建mock,mock一个接口
 List mockedList = mock(List.class);

 //使用mock对象
 mockedList.add("one");
 mockedList.clear();

 //验证行为
 verify(mockedList).add("one");
 verify(mockedList).clear();
 
 
 //mock具体的类
 LinkedList mockedList = mock(LinkedList.class);

 //stubbing 存根
 when(mockedList.get(0)).thenReturn("first");
 when(mockedList.get(1)).thenThrow(new RuntimeException());

 //prints "first"
 System.out.println(mockedList.get(0));

 //throws runtime exception
 System.out.println(mockedList.get(1));

 //prints "null" 因为get(999) 没有存根
 System.out.println(mockedList.get(999));

 //验证存根调用,但通常它只是多余的
 verify(mockedList).get(0);
 
  //使用内置的anyInt()参数匹配器进行存根
 when(mockedList.get(anyInt())).thenReturn("element");
 //prints "element"
 System.out.println(mockedList.get(999));

 //使用参数匹配器进行验证
 verify(mockedList).get(anyInt());
 

@RunWith(MockitoJUnitRunner.class)    (2)
public class ArticleManagerTest {

   @Mock private ArticleCalculator calculator;
   @Mock private ArticleDatabase database;
   @Mock private UserProvider userProvider;

   private ArticleManager manager;
   
   @Rule public MockitoRule rule = MockitoJUnit.rule();    (3)
   
   @Before  
	public void initMocks() {  
		MockitoAnnotations.initMocks(this);  (1)
	}
}
public class MockitoTest {
    //自动将mock字段注入测试对象。
    @InjectMocks private UserServiceImpl userServiceImpl;
    @Mock private UserMapper mapper;
    @Rule public MockitoRule rule = MockitoJUnit.rule();

    @Test
    public void testGet() {
        MockitoAnnotations.initMocks(this);
        User user = new User();
        user.setName("huaAn");
        Mockito.when(mapper.get(0)).thenReturn(user);
        
        assertTrue(userServiceImpl.getUser(0).equals(user));
        verify(mapper).get(0);
    }
}

public class UserServiceImpl implements UserService{
    @Autowired
    private UserMapper mapper;
    @Override
    public User getUser(Integer id) {
        return mapper.get(id);
    }
}

原创声明,本文系作者授权云+社区发表,未经许可,不得转载。

如有侵权,请联系 yunjia_community@tencent.com 删除。

编辑于

cuizh的测试

1 篇文章1 人订阅

我来说两句

0 条评论
登录 后参与评论

扫码关注云+社区

领取腾讯云代金券