我們在項目中,經(jīng)常要編寫一個測試類XXXXXTest,其中一般會用到以下注解:
一、常用注解
1. @RunWith(PowerMockRunner.class)
JUnit將會調(diào)用@RunWith中指定的測試執(zhí)行類而不是JUnit默認(rèn)的執(zhí)行類。
2.@PrepareForTest({ExampleTestServer.class})
? ? ? ? 2.1 當(dāng)使用Mockito.whenNew方法時(下面的Mock測試),必須加此注解,此注解里寫的類是需要mock的new對象代碼所在的類。
? ? ? ? 2.2 當(dāng)需要使用mock final、mock static方法、mock private方法、mock系統(tǒng)類的靜態(tài)方法時,必須加此注解,此注解里寫的分別是該方法所在的類。
3.@InjectMocks
創(chuàng)建一個實例,其余用@Mock(或@Spy)注解創(chuàng)建的mock將被注入到用該實例中。
(通常在真正運行時,會使用@Autowired等方式完成自動注入。但是在單元測試中,沒有啟動spring框架,此時就需要@InjectMocks來完成依賴注入,@InjectMocks會將帶有@Mock以及@Spy注解的對象注入到被測試的目標(biāo)類中:
- 在進行單元測試時,不應(yīng)初始化 Spring 上下文。因此,請@Autowired。
- 在進行集成測試時,應(yīng)使用真正的依賴項。所以去掉Mock)
4.@Mock
@Mock:創(chuàng)建一個Mock。
5.@Test
被打上該注解的方法,表示為一個測試方法。
二、Mock測試
1.Stub打樁
Mockito 中 when().thenReturn(); 這種語法來定義對象方法和參數(shù)(輸入),然后在 thenReturn 中指定結(jié)果(輸出)。此過程稱為 Stub 打樁 。一旦這個方法被 stub 了,就會一直返回這個 stub 的值。
Mockito.when(request.getParameter("csdn")).thenReturn("lirenji");
注意:
- 對于 static 和 final 方法, Mockito 無法對其 when(…).thenReturn(…) 操作。
- 當(dāng)我們連續(xù)兩次為同一個方法使用 stub 的時候,他只會只用最新的一次。
2.迭代打樁
第一次調(diào)用 i.next() 將返回 ”Hello”,第二次的調(diào)用會返回 ”World”。
// 方法一 (三個方法等價)
when(i.next()).thenReturn("Hello").thenReturn("World");
// 方法二
when(i.next()).thenReturn("Hello", "World");
// 方法三
when(i.next()).thenReturn("Hello"); when(i.next()).thenReturn("World");
3.拋出異常
//一般情況
when(i.next()).thenThrow(new RuntimeException());
// void 方法的
doThrow(new RuntimeException()).when(i).remove();
// 迭代風(fēng)格 (第一次調(diào)用 remove 方法什么都不做,第二次調(diào)用拋出 RuntimeException 異常)
doNothing().doThrow(new RuntimeException()).when(i).remove();
4.Any
anyString()
?匹配任何 String 參數(shù),anyInt()
?匹配任何 int 參數(shù),anySet()
?匹配任何 Set,any()
?則意味著參數(shù)為任意值?any(User.class)
?匹配任何 User類。
when(mockedList.get(anyInt())).thenReturn("element");
System.out.println(mockedList.get(999));// 此時打印是 element
System.out.println(mockedList.get(777));// 此時打印是 element
?Example:
有如下代碼段:文章來源:http://www.zghlxwxcb.cn/news/detail-426019.html
@Service
public class MyService {
@Autowired
private MyRepository myRepository;
@Autowired
private YourRepository yourRepository;
public void doSomething() {
this.myRepository.doSomething();
}
}
測試類:文章來源地址http://www.zghlxwxcb.cn/news/detail-426019.html
@RunWith(MockitoJUnitRunner.class)
@PrepareForTest(MyService.class)
public class UserServiceTest {
@InjectMocks
private MyService myService;
@Mock
private MyRepository myRepository;
@Mock
private YourRepository yourRepository;
@Test
public void testInjectMocks() {
System.out.println(myService.getMyRepository().getClass());
}
}
到了這里,關(guān)于JAVA測試類注解以及Mock測試的文章就介紹完了。如果您還想了解更多內(nèi)容,請在右上角搜索TOY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!