KeykoYume
KeykoYume

Reputation: 2645

Unable to load test file using bazel

I have the following project structure:

project/
   - app/
   - test/
      - java/
         - Utils.java
      - resources/
         - file.json
         - BUILD.bazel
   - BUILD.bazel

I'm trying to load the file.json as a File object in order to use it to test some classes. In Utils.java, I try to read it as:

public class Utils {
    public static File getSnapshotTestData() {
        File file = new File(Utils.class.getClassLoader().getResource("file.json").getFile());

        // Added this part to test the file was loaded correctly
        try {
            String data = FileUtils.readFileToString(file, "UTF-8"); // throws FileNotFound Exception
            System.out.println("Data: " + data);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return file;
    }
}

Even though if file.getAbsolutePath() returns a path like /scratch/xxxx/.bazel/output/d03a9523f165711d724c4ed2c7f8d270/execroot/__main__/bazel-out/k8-opt/bin..., if I try to read the file, I get FileNotFound.

Any idea what might be wrong here?

Added in my bazel files the following:

project/BUILD.bazel

ARCHIVES = [
    "//xxx/xxx/app/src/test/resources:file.json",
]

java_junit5_test(
    name = "snapshot_admin_app_test",
    srcs = glob(["src/test/java/**/*.java"]),
    resources = glob(["src/test/resources/**/*.*"]) + ARCHIVES,
    test_package = "com.xxx.xxx",
    deps = DEPS + TESTING_DEPS,
)

project/test/resources/BUILD.bazel

exports_files(["file.json"])

Upvotes: 1

Views: 1090

Answers (2)

Pramod Kalipatnapu
Pramod Kalipatnapu

Reputation: 51

I had a similar issue with loading resource files from the src/main/resources folder. Below is the answer from the Bazel slack channel:

When you use bazel run on a java target, all resource files will be built into jars corresponding to their java_library targets meaning you can't use getFile on them directly. Try getResourceAsStream

If the files are in the data param, they will be available on $PWD when you use bazel run, but they won't be built into the deploy jar and they won't be on the class path

using getResourceAsStream did the trick for me

Upvotes: 1

Skk
Skk

Reputation: 188

You need to include this in the data attribute:

java_junit5_test(
    name = "snapshot_admin_app_test",
    srcs = glob(["src/test/java/**/*.java"]),
    resources = glob(["src/test/resources/**/*.*"]) + ARCHIVES,
    data = glob(["src/test/resources/**/*.*"]),
    test_package = "com.xxx.xxx",
    deps = DEPS + TESTING_DEPS,
)

Upvotes: 1

Related Questions