[英]File location for unit testing
This is a very simple question which I cannot find a solution for. 这是一个非常简单的问题,我找不到解决方案。 I have a quite complex Android app which uses the camera and does some manipulations to the images taken. 我有一个非常复杂的Android应用程序,它使用相机并对拍摄的图像进行一些操作。 I now want to write Unit tests for some of the functions but I cannot get a file loaded. 现在,我想为某些功能编写单元测试,但无法加载文件。
In an Android test project where should I paste the Image to test on and how can I load that image into a File
object? 在Android测试项目中,应将图像粘贴到哪里进行测试,以及如何将该图像加载到File
对象中? I have a normal junit.framework.TestCase
class that needs to send a File
to an class to test on. 我有一个普通的junit.framework.TestCase
类,需要将File
发送到一个类进行测试。 Thanks in advance! 提前致谢!
This may not be the best solution since it could bloat your project considerably. 这可能不是最佳解决方案,因为它可能会使您的项目project肿。 However, short of writing code to download an image in your test cases, I'm not sure what other approach there might be. 但是,由于没有编写代码来下载测试用例中的图像,因此我不确定还有其他方法。
Simply, i have 'test' drawables in my resources and I load them as bitmaps, then store them somewhere on the disc to finally reference them in my tests. 简而言之,我在资源中具有“测试”图形,然后将它们作为位图加载,然后将它们存储在光盘上的某个地方,以最终在测试中引用它们。 This is the code I use: 这是我使用的代码:
public File saveResourceImageToExternalStorage(Activity activity, String picFileName, int imageId)
{
Bitmap bitmap = BitmapFactory.decodeResource(activity.getResources(), imageId);
File picFile = null;
OutputStream os = null;
try
{
picFile = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES), picFileName);
picFile.createNewFile();
os = new FileOutputStream(picFile);
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, os);
}
catch (IOException e)
{
e.printStackTrace();
}
return file;
}
You'll probably want to make that method a little more robust. 您可能需要使该方法更可靠。
Finally, you could just stash your test images in your assets folder for your project. 最后,您可以将测试图像存储在项目的资产文件夹中。 Then you can get them from your assets folder using getAssets()
in an Activity or using the path which should be something like file:///android_asset/your_file_name.jpg
然后,您可以使用getAssets()
或使用应该类似于file:///android_asset/your_file_name.jpg
类的路径,从资产文件夹中获取它们。
EDIT 编辑
I think a better solution, after some research, would be to add your files to the assets of your test project and use InputStream input = this.getContext().getAssets().open("file.jpg");
我认为,经过一些研究,更好的解决方案是将文件添加到测试项目的资产中,并使用InputStream input = this.getContext().getAssets().open("file.jpg");
. 。 You need to call this from a class that inherits from InstrumentationTestCase
or, I suppose, ActivityInstrumentationTestCase2
. 您需要从从InstrumentationTestCase
继承的类(或者我想从ActivityInstrumentationTestCase2
继承)调用此ActivityInstrumentationTestCase2
。 You can then manipulate the input stream how you need 然后,您可以根据需要操纵输入流
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.