如何编写 Android 单元测试?

huangapple 未分类评论45阅读模式
英文:

How to write an android unit test?

问题

以下是您提供的内容的翻译部分:

我对***TDD(测试驱动开发)***编码方法还不熟悉。我知道我们必须编写一个失败的测试,然后编写最少量的代码使测试通过,我理解了基本的例子。但当我想在我的代码中实施它时,我卡住了。

以下是两个类MainActivity类ImageData类,我执行的任务非常简单,就是获取图像并计算其尺寸,然后检查是否有可用的内存来存储图像,并根据情况设置标签。现在,我想为我的ImageData类中的getMeasure()函数编写一个测试**(尽管我知道测试是首先编写的)。我无法理解的是,我应该从哪里获取图像来计算其尺寸。我应该将图像保存在Drawable文件夹中(在桌面上),还是有办法从我的Android设备中选择图像进行测试。

下面是这些类的代码:

MainActivity类:

代码部分略去

ImageData类:

代码部分略去

ADD:

  • 当我尝试获取宽度和高度时,它总是返回0。
BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
BitmapFactory.decodeResource(Resources.getSystem(), R.raw.disco_light);
int width = options.outWidth;
int height = options.outHeight;
  • 至于内存,测试中是否应该默认采用任何值(图像大小与可用内存进行了比较)?
英文:

I am new to the TDD(Test- Driven Development) approach of writing codes. I know that we have to write a test which fails and then we have to write a minimal amount of code that would pass the test and I understood the basic examples. But when I wanted to implement it in my code, I was stuck.

Below are two classes MainActivity class and ImageData class and the task I am performing is pretty simple which is to take an image and calculate its dimensions and to check if there is available memory for the image and I am setting the label accordingly. Now, I want to write a test(Though I know that tests are written first.) for getMeasure() function in my ImageData class. The thing that I cannot understand is from where should I take the image for calculating it's dimensions. Should I save the image in the Drawable folder(in the desktop.) or is there a way to choose the image from my android device for the test.

Below are the classes:

MainActivity class:

package com.example.test;

import android.app.Activity;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.StatFs;
import android.provider.MediaStore;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import java.io.File;

import static android.provider.Telephony.ThreadsColumns.ERROR;

public class MainActivity extends Activity {


    private static int LOAD_IMAGE = 1;


    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        Button buttonLoadImage = findViewById(R.id.space);
        buttonLoadImage.setOnClickListener((View view)-> {
                Intent i = new Intent(
                        Intent.ACTION_PICK,
                        android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
                startActivityForResult(i, LOAD_IMAGE);
        });
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (requestCode == LOAD_IMAGE && resultCode == RESULT_OK && data != null) {
            Uri selectedImage = data.getData();

            //getting the image detail
            String[] filePathColumn = { MediaStore.Images.Media.DATA };
            Cursor cursor = getContentResolver().query(selectedImage,
                    filePathColumn, null, null, null);
            cursor.moveToFirst();
            int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
            String picturePath = cursor.getString(columnIndex);

            //calculating dimension of the image
            ImageData imageData = new ImageData(new File(picturePath));
            int[] a = new int[2];
            a = imageData.getMeasure();
            double size = a[0] * a[1] ;
            size /= (8*1024*1024.0);
            size *= 32;

            //Setting textview
            TextView storage = findViewById(R.id.storage);
            storage.setText("Available storage : "+getAvailableExternalMemorySize());
            TextView image = findViewById(R.id.image);
            image.setText("Size of Image : "+size);
            TextView available =  findViewById(R.id.available);

            double memory = Double.parseDouble(getAvailableExternalMemorySize());
            if(size < memory)
                available.setText("It can be displayed on the image view.");
            else if(size > memory)
                available.setText("It cannot be displayed on the image view without compressing.");

        }
    }

    public static boolean externalMemoryAvailable() {
        return android.os.Environment.getExternalStorageState().equals(
                android.os.Environment.MEDIA_MOUNTED);
    }

    public static String getAvailableExternalMemorySize() {
        if (externalMemoryAvailable()) {
            File path = Environment.getExternalStorageDirectory();
            StatFs stat = new StatFs(path.getPath());
            long blockSize = stat.getBlockSizeLong();
            long availableBlocks = stat.getAvailableBlocksLong();
            return String.valueOf(((availableBlocks * blockSize)/(1024*1024.0)));
        } else {
            return ERROR;
        }
    }
}

ImageData class:

package com.example.test;

import android.graphics.BitmapFactory;
import androidx.annotation.NonNull;
import java.io.File;

public class ImageData {

    private transient File file;

    public ImageData(@NonNull File file) {
        this.file = file;
        String fileName = file.getName();
    }

    public int[] getMeasure() {
        BitmapFactory.Options options = new BitmapFactory.Options();
        options.inJustDecodeBounds = true;
        BitmapFactory.decodeFile(file.getAbsolutePath(), options);
        int width = options.outWidth;
        int height = options.outHeight;

        return new int[] {width, height};
    }

}

Thanks.

ADD:

  • When I am trying to get the width and height it is always returning 0.

.

BitmapFactory.Options options = new BitmapFactory.Options();
		options.inJustDecodeBounds = true;
		BitmapFactory.decodeResource(Resources.getSystem(), R.raw.disco_light);
		int width = options.outWidth;
		int height = options.outHeight;
  • And for memory, should it be taken any value by default(The image size is checked with the available memory.) for the test?

huangapple
  • 本文由 发表于 2020年4月10日 22:59:11
  • 转载请务必保留本文链接:https://java.coder-hub.com/61142999.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定