Provide test rule to use resource from classpath instead of working directory

We often see the pattern that developers load resources for tests directly from the current directory and not from the classpath. This leads to problem when the tests are executed in a different working directory.

Non-compliant:
new File(“src/test/resources/foo.txt”);

compliant:
this.getClass().getClassLoader().getResourceAsStream(“foo.txt”)

I see several difficulties related to such a rule:

  • The java analyzer does not resolve maven configuration and does not know which folder are test resource directories in a project (even if we can assume that it’s mainly “src/test/resources”)
  • In your example, NonCompiant is a File and Compliant is an InputStream, it’s not at all the same kind of object and the same usage. If you need a File in your test you have no choice. We can only propose a replacement when you try to convert this File into a byte or a String
  • Before java 9 there’s no standard method to convert “getResourceAsStream(…)” into a byte or a String
  • Since java 9, using byte[] data = this.getClass().getClassLoader().getResourceAsStream("/foo.txt").readAllBytes(); is longer that Files.readAllBytes(Paths.get("src", "test", "resources", "foo.txt"))
  • Build tools like maven usually properly set the current directory while building a module, and IDEs should also set them properly. Users will not understand why a rule bothers then with this useless replacement in their context. For example, the java analyzer source code itself has a lot of references to src/test/resources without any test execution issues (For example, Intellij Idea use MODULE_WORKING_DIR as working directory for the tests)