Java 如何编写android单元测试?

Java 如何编写android单元测试?,java,android,unit-testing,android-studio,tdd,Java,Android,Unit Testing,Android Studio,Tdd,我不熟悉TDD(测试驱动开发)编写代码的方法。我知道我们必须编写一个失败的测试,然后我们必须编写最少的代码才能通过测试,我理解了基本示例。但当我想在代码中实现它时,我被卡住了 下面是两个类MainActivity类和ImageData类,我执行的任务非常简单,即拍摄图像并计算其尺寸,检查图像是否有可用内存,并相应地设置标签。现在,我想为我的ImageData类中的getMeasure()函数编写一个测试(尽管我知道测试是先编写的)。我无法理解的是,我应该从哪里拍摄图像来计算它的尺寸。我应该将图像

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

下面是两个类MainActivity类ImageData类,我执行的任务非常简单,即拍摄图像并计算其尺寸,检查图像是否有可用内存,并相应地设置标签。现在,我想为我的ImageData类中的getMeasure()函数编写一个测试(尽管我知道测试是先编写的)。我无法理解的是,我应该从哪里拍摄图像来计算它的尺寸。我应该将图像保存在Drawable文件夹(桌面)中,还是有办法从android设备中选择图像进行测试

以下是课程:

main活动类:

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;
        }
    }
}
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};
    }

}
谢谢

添加:

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;
        }
    }
}
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};
    }

}
  • 当我尝试获取宽度和高度时,它总是返回0

  • 对于内存,默认情况下是否应该取任何值(使用可用内存检查图像大小。)进行测试

如果我理解正确,这是关于将图像文件放在哪里进行测试的问题:看看这篇老文章,这个概念仍然有效,但它被弃用了,不是吗?代码可能会被弃用(很可能会,因为唯一不变的事情(尤其是android开发)是更改;-))但我的意思是向您展示文件夹结构:在问题中,他们将包含测试数据的文件放在测试文件夹下,而不是主文件夹下谢谢。您能告诉我更多关于如何访问该图像(计算其尺寸)的信息吗?上面的问题似乎对我不起作用。你是说喜欢吗?