我有两个服务
服务A
服务B
我正在测试服务A。服务A注入了服务B的依赖项。服务B需要一个JSoup连接,因此我试图模拟这个JSoup连接。服务B中的连接由Bean ConnectionHandler处理,因此我尝试:
创建真正的服务A实例使用MockServiceB注入服务A实例使用MockConnectionHandler注入MockServiceB(并从中模拟方法调用(
这可能吗?
如果要进行单元测试,则应单独测试Service A
。为此,您应该创建一个Service B
的mock,并将其注入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));
}