Write jUnit test to check service with json files
Task: Write jUnit test file which will call service method with input json and check response json
Implementation (Draft version):
package myapp;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import java.nio.charset.Standardcharsets;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.Objects;
import org.json.JSONObject;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.CsvSource;
import org.skyscreamer.jsonassert.JSONAssert;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.ActiveProfiles;
@SpringBootTest(classes App.class)
@ActiveProfiles(("dev", "db"])
class EventTransformerTest(
@Autowired
private MyService transformer;
private final ObjectMapper objectMapper = new ObjectMapper();
@ParameterizedTest
@csvsource((
"data/in1.json, data/out1.json",
"data/in2.json, data/out2.json",
"data/in3.json, data/out3.json",
"data/in4.json, data/out4.json",
]}
public void myServiceIT(String payloadFilename, string responseFilename) throws Exception (
String payloadstring = new String(
Files.readAllBytes(Paths.get(
Objects.requireNonNulL(
Thread.currentThread()
.getContextclassLoader()
.getResource(payloadFilename)
.toURI())), StandardCharsets.UTF_8);
JsonNode eventNode = objectMapper.readTree(payloadString);
String eventstring = eventNode.get("Event").tostring();
OutEvent inEvent = objectMapper.readValue(eventString, InEvent.class );
String correctResponseString = new String(
Files.readAllBytes(
Paths.get(
Objects.requireNonNull(
Thread.currentThread()
.getContextClassLoader()
.getResource(responseFilename))
toURI())),StandardCharsets.UTF_8);
OutEvent result = transformer.transform(inEvent);
Assertions.assertNotNull(result);
Assertions.assertNotNull(result.getTxt());
...
String resultstring = objectMapper.writeValueAsstring(result);
JSONAssert.assertEquals(correctResponseString, new JSONObject(resultString), strict: false);
}
}
Done.