@Mock與@InjectMocks一般搭配組合使用,是單元測試必不可少的注解
@Mock:需要模擬的類,我們需要模擬哪些類,就用它修飾哪些類的變量,常用于第三方服務(wù)service
@InjectMocks:要測試的類,使用@Mock修飾的對象,就是我們測試哪個類,就用它修飾對應(yīng)的變量,會整合使用@Mock修飾的對象文章來源:http://www.zghlxwxcb.cn/news/detail-740934.html
直接上代碼文章來源地址http://www.zghlxwxcb.cn/news/detail-740934.html
@Service
public class ThirdService {
public Object getThirdUser(String userId) {
return new Object();
}
}
@Service
public class UserService {
@Autowired
private ThirdService thirdService;
public Object getUser(String userId) {
return thirdService.getThirdUser(userId);
}
}
//測試UserService
@SpringBootTest
class UserServiceTest {
//需要模擬的類(因?yàn)閁serService中使用了這個類)
@Mock
private ThirdService thirdService;
//要測試的類,使用@Mock修飾的對象
//這時候userService對象中持有的thirdService變量就是模擬的對象了
@InjectMocks
private UserService userService;
@Test
public void testGetUser() {
//設(shè)定行為返回數(shù)據(jù),我們可以設(shè)定模擬對象的行為,當(dāng)然也可以不設(shè)定
//any代表任意參數(shù),返回a對象
Object a = new Object();
when(thirdService.getThirdUser(any())).thenReturn(a);
//執(zhí)行被測試的方法,這時候內(nèi)部調(diào)用的ThirdService就是模擬對象了,行為結(jié)果就是上面設(shè)置的
Object abc = userService.getUser("abc");
//驗(yàn)證結(jié)果
assertEquals(a,abc);
}
}
到了這里,關(guān)于單元測試之@Mock與@InjectMocks(一文搞懂)的文章就介紹完了。如果您還想了解更多內(nèi)容,請?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!