gmazzo/okhttp-client-mock

Failed to match rule with specific URL

skaldarnar opened this issue · 2 comments

Hi,

I'm using this lib to replace some mocking code and wanted to add a rule for GET requests to a specific URL - basically the "Hello World" example:

https://github.com/MovingBlocks/TerasologyLauncher/blob/91d2056e11cf7cb6bd63474ffecc035e284d47ce/src/test/java/org/terasology/launcher/repositories/JenkinsClientTest.java#L58-L68

        final var interceptor = new MockInterceptor();
        interceptor.addRule()
                //TODO: I'd like to specify the URL here, but then matcher does not match.
                //      Somehow, the matcher surrounds the expected URL with some weird characters.
                //      expected=\Qhttps://jenkins.example\E;actual=https://jenkins.example/; matcher=url(~=\Qhttps://jenkins.example\E)
                .get()
                .respond("{ this is ] no json |[!");

        final var httpClient = new OkHttpClient.Builder()
                .addInterceptor(interceptor)
                .build();

However, I see a matching exception which I don't understand:

java.lang.AssertionError: Not matched next rule: [method(GET), url(~=\Qhttps://jenkins.example\E)], consumed=false, request=Request{method=GET, url=https://jenkins.example/}
Failed to match:
	1: expected=\Qhttps://jenkins.example\E;actual=https://jenkins.example/; matcher=url(~=\Qhttps://jenkins.example\E)
	at okhttp3.mock.MockInterceptor.intercept(MockInterceptor.java:129)
	at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.kt:109)
	at okhttp3.internal.connection.RealCall.getResponseWithInterceptorChain$okhttp(RealCall.kt:201)
	at okhttp3.internal.connection.RealCall.execute(RealCall.kt:154)
	at org.terasology.launcher.repositories.JenkinsClient.request(JenkinsClient.java:66)

Where do the surrounding \Q and \E come from? What am I missing here?

URLMatcher works with Pattern. \Q and \E are the quoting escape sequence for literal matches as defined in https://docs.oracle.com/javase/7/docs/api/java/util/regex/Pattern.html#quote(java.lang.String)#quot

The problem seems to be that you are expecting https://jenkins.example but the actual URL is https://jenkins.example/.

Have you tried this?

final var interceptor = new MockInterceptor();
        interceptor.addRule()
                .get("https://jenkins.example/")
                .respond("{ this is ] no json |[!");

or this?

final var interceptor = new MockInterceptor();
        interceptor.addRule()
                .get()
                .urlStarts("https://jenkins.example")
                .respond("{ this is ] no json |[!");

Thanks for the explanation (and sorry for not coming back to this for such a long time 🙈 )

I indeed missed the difference in the expected URL, my bad. All working fine on my end now, closing this issue.