You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何Mock带有Lambda表达式的方法?以Resteasy ClientBuilder为例

Mocking hostnameVerifier with Lambda Parameter in PowerMockito for ResteasyClientBuilder

Hey there! You’re already doing great mocking the static ResteasyClientBuilder and the sslContext method. Let’s get that hostnameVerifier method with the lambda sorted out—here’s exactly how to do it:

Step-by-Step Implementation

First, ensure you have a mock instance of ResteasyClientBuilder set up (you likely already have this, but just to confirm):

ResteasyClientBuilder clientBuilder = Mockito.mock(ResteasyClientBuilder.class);

Then, extend your existing mocks with the hostnameVerifier mock. The key here is recognizing that your lambda (s1,s2)-> true is just an anonymous implementation of the HostnameVerifier interface. We can use an argument matcher to target this interface:

// Mock the static ResteasyClientBuilder class
PowerMockito.mockStatic(ResteasyClientBuilder.class);
PowerMockito.when(ResteasyClientBuilder.newBuilder()).thenReturn(clientBuilder);

// Mock the sslContext chained method call
PowerMockito.when(clientBuilder.sslContext(Mockito.any(SSLContext.class))).thenReturn(clientBuilder);

// Mock hostnameVerifier to accept any HostnameVerifier implementation (your lambda)
PowerMockito.when(clientBuilder.hostnameVerifier(Mockito.any(HostnameVerifier.class))).thenReturn(clientBuilder);

Why This Works

Lambdas that implement a single-method interface (like HostnameVerifier) are compiled into instances of that interface at runtime. Using Mockito.any(HostnameVerifier.class) tells PowerMockito to match any instance of this interface—perfect for your lambda argument.

Bonus: Validate Lambda Behavior

If you want to ensure the lambda you’re passing behaves as expected (returns true for any host/session), you can use a custom argument matcher with argThat:

PowerMockito.when(clientBuilder.hostnameVerifier(ArgumentMatchers.argThat(verifier -> {
    // Verify the lambda returns true for any input
    return verifier.verify("test-host", null);
}))).thenReturn(clientBuilder);

This not only mocks the method call but also validates that your production lambda has the correct behavior.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.22 07:58:00