lelloman
lelloman

Reputation: 14173

FileNotFoundException when trying to read assets with Roboelectric

I'm trying to run a test that needs access to a file in the assets folder using roboelectric 3.3.2 with

RuntimeEnvironment.application.getAssets().open("my_file");

but I always get this error

java.io.FileNotFoundException: build/intermediates/bundles/debug/assets/my_file (No such file or directory)

The thing I really fail to understand is that even if I specify a path for the assets dir this way

@Config(constants = BuildConfig.class, sdk = 23, assetDir = "/home/")

I still get the same error, I mean the error with the same path build/intermediates... so, the assetDir value is being ignored? Or am I missing something here?

Is it possible to open a file from the assets folder without too much hassle?

EDIT

as suggested I tried copying assets file to test/resources folder but I'm still getting the same error, still the same FileNotFoundException with build/itermediates.. path

android {
    sourceSets {
        String sharedTestJavaDir = 'src/sharedTest/java'

        test {
            java.srcDirs += [sharedTestJavaDir]
        }
        androidTest {
            java.srcDirs += [sharedTestJavaDir]
            resources.srcDirs += ['src/test/resources']
        }
    }
}

Upvotes: 5

Views: 2035

Answers (2)

Ahmed na
Ahmed na

Reputation: 1154

for Roboelectric to work just like android device put this in build.gradle

android {
  testOptions {
    unitTests {
      includeAndroidResources = true
    }
  }
}

Upvotes: 4

KOTIOS
KOTIOS

Reputation: 11194

Roboletric wont be able to read actual device assert folder so you have to virtually define some location and dump your resources to that path as below code :

For robolectric you have to define assert path as below :

android {
    sourceSets {
        String sharedTestJavaDir = 'src/sharedTest/java'

        test {
            java.srcDirs += [sharedTestJavaDir]
        }
        androidTest {
            java.srcDirs += [sharedTestJavaDir]
            resources.srcDirs += ['src/test/resources']
        }
    }
}

Access fixture files from your androidTest env this way:

this.getClass().getClassLoader().getResourceAsStream(filename);

Upvotes: 3

Related Questions