Skip to content

Instantly share code, notes, and snippets.

@SingingBush
Created May 8, 2023 10:38
Show Gist options
  • Save SingingBush/960cfe3f1616626b0538ce195c9d82b1 to your computer and use it in GitHub Desktop.
Save SingingBush/960cfe3f1616626b0538ce195c9d82b1 to your computer and use it in GitHub Desktop.
Matching json with mockito

Now you can use json string as argument matchers

when(myMock.methodCall(jsonEq("{\"firstName\":\"Bill\", \"lastName\":\"Gates\"}"))).thenReturn(myResponse);

or

verify(myMock, times(1)).methodCall(jsonEq("{\"firstName\":\"Bill\", \"lastName\":\"Gates\"}")));

which is useful as it'll be safer than testing with raw string values. This approach allows the json structure to have the fields in any order and will also match regardless of multiple lines or minimal whitespace.

import org.mockito.ArgumentMatcher;
// javax.json:javax.json-api
//import javax.json.Json;
//import javax.json.JsonStructure;
//import javax.json.stream.JsonGenerator;
// jakarta.json:jakarta.json-api
import jakarta.json.Json;
import jakarta.json.JsonStructure;
import jakarta.json.stream.JsonGenerator;
import java.io.IOException;
import java.io.Serializable;
import java.io.StringReader;
import java.io.StringWriter;
import java.util.Collections;
import java.util.Map;
import static org.mockito.ArgumentMatchers.argThat;
/**
* Reusable code for test classes
*
*/
public class TestUtils {
public static String jsonEq(String val) {
// if this was inside mockito it'd be reportMatcher(new JsonEquals(val));
argThat(new JsonEquals(val));
return val;
}
static class JsonEquals implements ArgumentMatcher<String> {
private static final Map<String, Object> OPTIONS = Collections.singletonMap(JsonGenerator.PRETTY_PRINTING, true);
private final String value;
private final JsonStructure json;
public JsonEquals(final String value) {
if (value == null) throw new IllegalArgumentException("string value is null");
this.value = value;
this.json = Json.createReader(new StringReader(value)).read();
}
@Override
public boolean matches(String arg) {
final JsonStructure argJson = Json.createReader(new StringReader(arg)).read();
return json.equals(argJson);
}
@Override
public String toString() {
try (final StringWriter writer = new StringWriter()) {
Json.createWriterFactory(OPTIONS)
.createWriter(writer)
.write(json);
return writer.toString();
} catch (final IOException e) {
e.printStackTrace();
return value;
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment