0

The test method below passes when my test class is in the default package and fails when I move it into a package.

The directory structure is the following:

src/
  main/
    java/
      some.package/
    resources/
  test/
    FooTest.java // works here
    some.package/
        FooTest.java // does not work here

public class FooTest {

@Test
public void TestLoadImageFromFile() {
    BufferedImage loadedImage = null;
    try {
        loadedImage = ImageIO.read(this.getClass().getResource("someImage.png"));
    } catch(IOException e) {
        e.printStackTrace();
    }
    assertNotNull(loadedImage);
}
...
AnthonyW
  • 1,910
  • 5
  • 25
  • 46
  • getClass().getResource() uses the class loader to load the resource. This means that the resource must be in the classpath to be loaded. – StackFlowed Nov 03 '14 at 16:52
  • Why would it work in one location but not the other if it is missing from the classpath? Shouldn't it not work at all? – AnthonyW Nov 03 '14 at 16:57
  • The linked question is COMPLETELY irrelevant. It uses ClassLoader#getResource and addresses a different problem. – AnthonyW Nov 03 '14 at 17:05

1 Answers1

2

As is, your path is relative to the calling class. Use /someImage.png instead.

sp00m
  • 47,968
  • 31
  • 142
  • 252