'Unit testing on local file throws java.io.FileNotFoundException in macbook

 response =
        File("src\\test\\java\\com\\resources\\products\\response.json").bufferedReader()
            .use { it.readText() }

I have this line of code for mocking response and it is working fine on pc but throws not found on macbook? Any solutions? Thanks.



Solution 1:[1]

You can create assets directory in unit test dir(java unit test), and put your response.json into it. and then you can read this file with these code below:

private static File readAssetsFile(String fileName) {
    // create file for assets file
    final String dir = System.getProperty("user.dir");
    File assetsDir = new File(dir, File.separator + "src/test/assets/");
    return new File(assetsDir, fileName);
}

private static String streamToString(InputStream inputStream)
        throws IOException {
    if (inputStream == null) {
        return "";
    }
    StringBuilder sBuilder = new StringBuilder();
    String line;
    BufferedReader bufferedReader = new BufferedReader(
            new InputStreamReader(inputStream));
    while ((line = bufferedReader.readLine()) != null) {
        sBuilder.append(line).append("\n");
    }
    return sBuilder.toString();
}

// YOUR TESTCASE
@Test
public void testReadResponseJson() throws IOException {
    File respFile = readAssetsFile("response.json");
    String respText = streamToString(new FileInputStream(respFile));
    assertEquals("{}", respText);
}

Solution 2:[2]

I have solved with:

 val home = System.getProperty("user.home")
    val file = File(home + File.separator + "Desktop" + File.separator + "response.json")

Desktop directory for the sample. I will give the absolute path step by step.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Phil
Solution 2 dgncn