[英]Mocking a bean that is levels down from the unit being tested
我有 2 項服務
服務A
服務乙
我正在測試服務 A。服務 A 獲取注入的服務 B 依賴項。服務 B 需要 JSoup 連接,因此我試圖模擬這個 Jsoup 連接。 服務 B 中的連接由 Bean ConnectionHandler 處理,因此我試圖:
創建真正的服務 A 實例 使用 MockServiceB 注入服務 A 實例 使用 MockConnectionHandler 注入 MockServiceB (並從那里模擬方法調用)
這可能嗎?
如果要進行單元測試,則應單獨測試Service A
為此,您應該創建一個Service B
的模擬並將其注入到Service A
。 您應該模擬完整的Service B
,並讓Service A
調用的方法返回您需要的值。 因此, Service B
根本不需要MockConnectionHandler
。
public class ServiceA {
private ServiceB serviceB;
@Inject
public void setServiceB(ServiceB serviceB) {
this.serviceB = serviceB;
}
public MonthlyStatistic createStatistics(int categoryId) {
List<DailyStatistic> data = serviceB.fetchData(categoryId);
return computeMonthlyStatistic(data);
}
private void computeMonthlyStatistic(List<DailyStatistic> data) { ... }
}
public class Service B {
@Inject
private Connection connection;
public List<DailyStatistic> fetchData(int categoryId) {
return mapToDailyStatistics(queryDb(categoryId));
}
private List<DailyStatistic> mapToDailyStatistics(List<Row> rows) { ... }
private List<Row> queryDb(int categoryId) { ... }
}
@Test
public void testCreateStatistics() {
ServiceB mockedServiceB = mock(ServiceB.class);
when(mockedServiceB.fetchData(anyInt())).thenReturn(...);
ServiceA serviceUnderTest = new ServiceA();
serviceUnderTest.setServiceB(mockedServiceB);
assertEquals(..., serviceUnderTest.createStatistics(3));
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.