如何使用 Mockito 模拟 PoolDataSource?

How to mock PoolDataSource using Mockito?

我有一个 class 来获取我的连接池的指标:

@ApplicationScoped
public class ConnectionPoolMetrics {

    @Inject
    @Named("appDs")
    private PoolDataSource appDs;

    protected PoolDataSource getPoolDataSource() {
        return appDs;
    }

    @Gauge(unit = MetricUnits.NONE, name = "pool_connections_total_count", description = "Display the number of total connections in pool", absolute = true)
    public int getActiveConnectionsCount() {
        JDBCConnectionPoolStatistics stats = _getStatistics();
        if (null != stats) {
            return stats.getTotalConnectionsCount();
        }
        return 0;
    }

    private JDBCConnectionPoolStatistics _getStatistics() {
        PoolDataSource pds = getPoolDataSource();

        if (pds != null) {
            return pds.getStatistics();
        }

        return null;
    }

}

我想测试这个 class,方法是模拟 PoolDataSource 并使其成为 return 一些测试统计数据,以便我测试获取个人统计数据的方法。

我该怎么做?像下面这样的可能吗?

@ExtendWith(MockitoExtension.class)
public class ConnectionPoolMetricsTest {

    @InjectMocks
    ConnectionPoolMetrics connectionPoolMetrics;

    @Mock
    PoolDataSource testDs;

    @BeforeEach
    void setup() {
        Mockito.when(testDs.getStatistics()).thenReturn(<custom stats>);
    }

我能够通过以下方式测试 class:

@ExtendWith(MockitoExtension.class)
@DisplayName("ConnectionPoolMetrics Unit Tests")
public class ConnectionPoolMetricsTest {

    private static final int TOTAL_CONNECTIONS_COUNT = 2;

    @Spy
    ConnectionPoolMetrics connectionPoolMetrics;

    @Mock
    PoolDataSource testDs;

    @Mock
    JDBCConnectionPoolStatistics testStats;

    @BeforeEach
    void setup() {
        Mockito.when(connectionPoolMetrics.getPoolDataSource()).thenReturn(testDs);
    }

    @Test
    @DisplayName("getActiveConnectionsCount - Should return TOTAL_CONNECTIONS_COUNT")
    void testGetActiveConnectionsCount() {
        Mockito.when(testStats.getTotalConnectionsCount()).thenReturn(TOTAL_CONNECTIONS_COUNT);
        Mockito.when(testDs.getStatistics()).thenReturn(testStats);

        assertEquals(TOTAL_CONNECTIONS_COUNT, connectionPoolMetrics.getActiveConnectionsCount());
    }

    @Test
    @DisplayName("getActiveConnectionsCount - Should return 0 when PoolDataSource is null")
    void testGetActiveConnectionsCountWithNullPds() {
        Mockito.when(connectionPoolMetrics.getPoolDataSource()).thenReturn(null);

        assertEquals(0, connectionPoolMetrics.getActiveConnectionsCount());
    }
}