开发者

How to copy files from assets on setUp method from an android Junit ServiceTestCase?

开发者 https://www.devze.com 2023-03-18 10:29 出处:网络
I\'m writing JUnit test code for an android service implementation, and I have to initialize the tests with some files copied on sdcard. My class signature is like this:

I'm writing JUnit test code for an android service implementation, and I have to initialize the tests with some files copied on sdcard. My class signature is like this:

public class ImageServiceTest extends ServiceTestCase<ImageService>  

I'm trying to use this tip to copy the files from assets, but the getAssets() method needs to extends Activity class.

public void copyAssets() {
    AssetManager assetManager = getAssets();
    ...
}

So.. How I can copy files from assets to sdcard to setUp the junit test in android?

Thanks in advanced.

Ps:

'getSystemContext().getAssets();', 'getContext().getAssets();', 'getApplicationContext();' returns the Service Project context, not the test project context.

Now i'm trying t开发者_Python百科o use Instrumentation, however it demands an Activity and I'm working with a Service project. I'm looking how to use Instrumentation without an Activity...


Ok, it was pretty easy.

My major problem was get the context from test project to access their assets folder. But getContext() returns the main project context. So, to get test project context I create a new context passing the test package:

Context mTestAppContext = getContext().createPackageContext("com.project.myapp",
                Context.CONTEXT_IGNORE_SECURITY);

:-)


You can do this:

protected void setUp() throws Exception {
    super.setUp();
    AssetManager assets = getSystemContext().getAssets();
    InputStream input = assets.open("file.txt");
    assertNotNull(input);
}

but take into account that in this case assets should be in the Service main project.


There is also a hidden method, in AndroidTestCase, which provided what is needed. It can be exposed with introspection.

private Context getTestContext() throws Exception
{
  return (Context)getClass().getMethod("getTestContext").invoke(this);
}
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号