Reputation: 125
I'm testing a Spring Boot microservice with JUnit and I have a problem with the path of a folder that is placed inside the resources folder of the service.
To pass the test I have to put the absolute path of the folder, instead, when using the full application it works perfectly with the relative path. I have tried some translations from relative to absolute path but none of them worked, the test passes only if the absolute path is given, not computed.
These are my files:
JSONRequest.java:
String absolutePath = String.valueOf(Paths.get("DecryptService/src/main/resources/KEY_DECR/").toAbsolutePath());
System.out.println(absolutePath);
try (FileWriter file = new FileWriter(absolutePath + "/tmpFile.json")) {
file.write(result.get("json"));
file.flush();
} catch (IOException e) {
e.printStackTrace();
loggerApplicativeJSON.error("{} - failed to create the temporary file.", result.get("username"));
}
DecryptServiceApplicationTests.java:
@SpringBootTest
class DecryptServiceApplicationTests {
private static JSONRequest jsonRequest = null;
@BeforeAll
static void setUp() {
jsonRequest = new JSONRequest();
}
@Test
public void applicationStartTest() {
DecryptServiceApplication.main(new String[] {});
}
@Test
public void correctDecryptJSON(){
JSONObject json = new JSONObject();
try {
json.put("username", "luca");
json.put("json", "--- values ---");
} catch (JSONException e) {
e.printStackTrace();
}
String expectedResult ="Unit:";
assertThat(String.valueOf(jsonRequest.post(json.toString())), containsString(expectedResult));
}
}
Thank you in advance.
Upvotes: 1
Views: 1758
Reputation: 468
I think first you should answer the following question: are you writing an integration or a unit test?
At the moment you seem to be doing both, on the one had you're creating a JSONRequest object programmatically (more common from unit tests where you programmatically instantiate the object under test), but you're also starting up the whole Spring app.
If you're writing a unit test you're not really interested in testing that a particular path exists in a filesystem, you'd be more interested in testing the logic behaviour. (If you want to verify file writing in a test https://blogs.oracle.com/javamagazine/post/working-and-unit-testing-with-temporary-files-in-java).
If you're writing an integration test then you can see the path as a property of the application and could easily refactor the app so that it takes different values depending on your environment (live vs integration test).
In either case you probably need to refactor your code to separate the configuration part (what is currently in your code a hard coded string containing the path) to a property so that you can write the test you desire.
Upvotes: 2