如何Mock带有Lambda表达式的方法?以Resteasy ClientBuilder为例
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

