Home > Software design >  JUnit5: create new file in build directory
JUnit5: create new file in build directory

Time:03-25

I have a Spring Boot application that provides Open API specification by /api/open-api/v3 path. The idea is that I request the Open API JSON during test running and then write its content to the file in build folder. So, I could parse it later and generate documentation. I tried to do it like this:

Files.writeString(Path.of("src", "test", "resources", "open-api.json"), res.getBody());

It did write the the file to the src/test/resources folder but in the source code module itself. Not the result build folder. Is it possible to overcome this issue?

CodePudding user response:

@Test
@DisplayName("Create a file on the build diretory")
void createFileOnBuildDir() throws IOException {

    final URL buildRoot = getClass().getResource("/");
    final Path jsonFile = Path.of(buildRoot.getPath(), "open-api.json");
    Files.writeString(jsonFile, "{\"value\": 123}");
    System.out.println(jsonFile);
}

result

/home/myuser/projects/testproject/build/classes/java/test/open-api.json
$ cat /home/myuser/projects/testproject/build/classes/java/test/open-api.json
{"value": 123}

But, I guess the best answer for your need is https://github.com/Swagger2Markup/spring-swagger2markup-demo project's https://github.com/Swagger2Markup/spring-swagger2markup-demo/blob/master/src/test/java/io/github/robwin/swagger2markup/petstore/Swagger2MarkupTest.java

  • Related