Kong / unirest-java

Unirest in Java: Simplified, lightweight HTTP client library.
http://kong.github.io/unirest-java/
MIT License
2.58k stars 591 forks source link

NullPointerException in MockClient #475

Closed sulakm closed 1 year ago

sulakm commented 1 year ago

Describe the bug NullPointerException occures in MockClient if both path is body expectations are specified and path is not fullfilled. A clear and concise description of what the bug is.

To Reproduce MockClient mock = MockClient.register(); mock.expect(HttpMethod.POST, "myurl").body("test").thenReturn().withStatus(200); mock.verifyAll();

Proposed fix Please change the condition from expectedBody != null to expectedBodyStatus != null on the line in the link below: https://github.com/Kong/unirest-java/blob/ad1a81de55ce9423e5a44dfad3f35fc6de56ae17/unirest-mocks/src/main/java/kong/unirest/Invocation.java#L185 It makes more sense to test the reference you are using for method invocation. This reference is only set if the body is being evaluated.

  if(expectedBodyStatus != null){
    sb.append("Body:\n");
    sb.append("\t" + expectedBodyStatus.getDescription()); 
sulakm commented 1 year ago

Also it seems like the method in expect(HttpMethod, path) is ignored. I am not sure if it is a bug or intended feature. It is either a method or a path but not both.

I have specified DELETE like this mockClient.expect(HttpMethod.DELETE, "some url").thenReturn().withStatus(200); mockClient.verifyAll() was satisfied even though only PUT method was sent.

With more expect with different methods the first is used and the others cause UnirestAssertion, regardless of HttpMethod.

The cause is probably missing parentheses here: return this.method.equals(request.getHttpMethod()) && ( this.path == null || this.path.equalsIgnoreCase(p.baseUrl()); ) https://github.com/Kong/unirest-java/blob/ad1a81de55ce9423e5a44dfad3f35fc6de56ae17/unirest-mocks/src/main/java/kong/unirest/Routes.java#L60

ryber commented 1 year ago

this is resolved in the most recent releases

sulakm commented 1 year ago

@ryber Many thanks for fixing null expectedBodyStatus. Can you please also add parethenses after && operator on this line as sugested in comment above ? It is still missing in the latest revision.