mockito单元测试 Java
待测试的服务接口:
public interface ItemService { String getItemNameUpperCase(String itemId); }
预览
待测试的服务的实现类:
@Service public class ItemServiceImpl implements ItemService { @Resource private ItemRepository itemRepository; @Override public String getItemNameUpperCase(String itemId) { Item item = itemRepository.findById(itemId); if (item == null) { return null; } return item.getName().toUpperCase(); } } // 测试用例 import org.junit.Before; import org.junit.Test; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.MockitoAnnotations; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Mockito.*; public class ItemServiceTest { @Mock private ItemRepository itemRepository; @InjectMocks private ItemServiceImpl itemService; @Before public void setUp(){ MockitoAnnotations.initMocks(this); } /** * 如果从存储层查询到一个Item, 那么它的 name 将被转化为大写. */ @Test public void shouldReturnItemNameInUpperCase() { // Given Item mockedItem = new Item("it1", "Item 1", "This is item 1", 2000, true); when(itemRepository.findById("it1")).thenReturn(mockedItem); // When String result = itemService.getItemNameUpperCase("it1"); // Then verify(itemRepository, times(1)).findById("it1"); assertThat(result).isEqualTo("ITEM 1"); } }
Mockito 的更多高级用法请参考官方网站和框架配套 wiki。如果需要 mock 静态方法、私有函数等,可以学习 PowerMock, 拉取其源码通过学习单元测试来快速掌握其用法。
相关推荐
84224552 2020-05-31
85344193 2020-05-17
80487608 2014-07-04
zhengzf0 2019-05-29
lzjqcc 2019-05-29
宿命java 2019-10-28
whbing 2019-10-27
xiaoshengyige 2016-05-19
Elementvin 2010-08-27
蛰脚踝的天蝎 2010-08-27
不忘初心才能始终 2019-07-01
84334595 2016-08-23
89510091 2014-07-04
82384298 2013-06-03
82384298 2019-06-28
84334595 2019-06-28
85344193 2011-11-23