Java mockito單元測試實(shí)現(xiàn)過程解析
更新時(shí)間:2020年08月31日 09:41:22 作者:BigOrang
這篇文章主要介紹了Java mockito單元測試實(shí)現(xiàn)過程解析,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下
待測試的服務(wù)接口:
public interface ItemService {
String getItemNameUpperCase(String itemId);
}
預(yù)覽
待測試的服務(wù)的實(shí)現(xiàn)類:
@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);
}
/**
* 如果從存儲(chǔ)層查詢到一個(gè)Item, 那么它的 name 將被轉(zhuǎn)化為大寫.
*/
@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 的更多高級用法請參考官方網(wǎng)站和框架配套 wiki。如果需要 mock 靜態(tài)方法、私有函數(shù)等,可以學(xué)習(xí) PowerMock, 拉取其源碼通過學(xué)習(xí)單元測試來快速掌握其用法。
以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
Java中的遞歸詳解(用遞歸實(shí)現(xiàn)99乘法表來講解)
這篇文章主要介紹了Java中的遞歸詳解(用遞歸實(shí)現(xiàn)99乘法表來講解),本文給出了普通的99乘法實(shí)現(xiàn)方法和用遞歸實(shí)現(xiàn)的方法,并對比它們的不同,體現(xiàn)出遞歸的運(yùn)用及理解,需要的朋友可以參考下2015-03-03
Spring實(shí)戰(zhàn)之屬性覆蓋占位符配置器用法示例
這篇文章主要介紹了Spring實(shí)戰(zhàn)之屬性覆蓋占位符配置器用法,結(jié)合實(shí)例形式分析了Spring屬性覆蓋占位符配置器相關(guān)原理、配置與使用技巧,需要的朋友可以參考下2019-12-12
SpringBoot詳細(xì)講解靜態(tài)資源導(dǎo)入的實(shí)現(xiàn)
在Web開發(fā)過程中,我們需要接觸許多靜態(tài)資源,如CSS、JS、圖片等;在之前的開發(fā)中,這些資源都放在Web目錄下,用到的時(shí)候按照對應(yīng)路徑訪問即可。不過在SpringBoot項(xiàng)目中,沒有了Web目錄,那這些靜態(tài)資源該放到哪里去,又要如何訪問呢?這就是我們要講的靜態(tài)資源導(dǎo)入2022-05-05

