You need to enable JavaScript to run this app. 如何编写带代码覆盖率的Spring @Bean单元测试(Mock acquireToken场景)
优惠活动
大模型
产品
解决方案
定价
更多

如何编写带代码覆盖率的Spring @Bean单元测试(Mock acquireToken场景)

方案1:使用Mockito(优先推荐,兼容性更好)

先调整原代码的可测试性,避免方法内硬实例化依赖对象:

  1. 把ConfidentialClientApplication的实例逻辑抽成独立Bean,方便测试时替换:
@Bean
public ConfidentialClientApplication confidentialClientApplication() throws Exception {
    PKCS8EncodedKeySpec spec = new PKCS8EncodedKeySpec(Files.readAllBytes(Paths.get(KeyPath)));
    PrivateKey key = KeyFactory.getInstance("RSA").generatePrivate(spec);

    InputStream certStream = new ByteArrayInputStream(Files.readAllBytes(Paths.get(CertPath)));
    X509Certificate cert = (X509Certificate) CertificateFactory.getInstance("X.509").generateCertificate(certStream);
    // 原有app初始化逻辑移到此处
    return ConfidentialClientApplication.builder(clientId, ClientCredentialFactory.createFromCertificate(key, cert))
            .authority(authority)
            .build();
}

@Bean
public IAuthenticationResult getAccessTokenByClientCredentialGrant(ConfidentialClientApplication app) throws Exception {
    ClientCredentialParameters clientCredentialParam = ClientCredentialParameters.builder(
            Collections.singleton(scope))
            .build();
    CompletableFuture<IAuthenticationResult> future = app.acquireToken(clientCredentialParam);
    return future.get();
}
  1. 单元测试代码,用@MockBean替换Spring上下文中的真实Bean:
@SpringBootTest
public class AuthConfigTest {
    // 替换容器中的真实ConfidentialClientApplication实例
    @MockBean
    private ConfidentialClientApplication app;
    
    @Autowired
    private IAuthenticationResult authResult;
    
    @Mock
    private IAuthenticationResult mockResult;

    @Test
    public void testGetAccessTokenBean() throws Exception {
        // 构造mock的异步返回结果
        CompletableFuture<IAuthenticationResult> mockFuture = CompletableFuture.completedFuture(mockResult);
        // 匹配参数mock acquireToken方法
        when(app.acquireToken(any(ClientCredentialParameters.class))).thenReturn(mockFuture);
        
        // 验证Bean创建正常,返回结果符合预期
        assertNotNull(authResult);
        assertEquals(mockResult, authResult);
        // 验证方法调用次数符合逻辑
        verify(app, times(1)).acquireToken(any(ClientCredentialParameters.class));
    }
}

方案2:无需修改原代码,用PowerMock mock局部实例

如果app是在getAccessTokenByClientCredentialGrant方法内部实例化、不方便抽成Bean的场景,可以用PowerMock mock构造方法:

  1. 先引入和你当前Mockito版本匹配的PowerMock依赖
  2. 测试代码如下:
@RunWith(PowerMockRunner.class)
@PowerMockRunnerDelegate(SpringRunner.class)
@SpringBootTest
@PrepareForTest(ConfidentialClientApplication.class)
public class AuthConfigTest {
    @Mock
    private ConfidentialClientApplication mockApp;
    @Mock
    private IAuthenticationResult mockResult;

    @Test
    public void testBeanCreation() throws Exception {
        // mock ConfidentialClientApplication的构造逻辑,返回自定义mock对象
        PowerMock.whenNew(ConfidentialClientApplication.class).withAnyArguments().thenReturn(mockApp);
        // mock acquireToken的返回结果
        CompletableFuture<IAuthenticationResult> mockFuture = CompletableFuture.completedFuture(mockResult);
        when(mockApp.acquireToken(any(ClientCredentialParameters.class))).thenReturn(mockFuture);
        
        // 直接调用配置类方法验证逻辑
        IAuthenticationResult result = AuthConfig.getAccessTokenByClientCredentialGrant();
        assertNotNull(result);
        assertEquals(mockResult, result);
    }
}

额外说明

如果不需要启动完整Spring上下文做纯单元测试,可以直接实例化配置类调用对应方法配合Mock验证,执行速度会更快。如果要mock静态方法逻辑,可以用PowerMock的mockStatic方法处理。

内容的提问来源于stack exchange,提问作者user14734781

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.18 00:06:08