android junit test中的错误,因为在创建时活动不可用的服务

时间:2012-03-12 06:29:01

标签: android junit

java.lang.IllegalStateException: System services not available to Activities before onCreate()
    at android.app.Activity.getSystemService(Activity.java:3536)
    at android.accounts.AccountManager.get(AccountManager.java:261)
    at com.android.deviceintelligence.activity.DeviceIntelligence.emailAccounts(DeviceIntelligence.java:466)
    at com.android.deviceintelligence.test.Testnew.testEmailAccounts(Testnew.java:32)
    at java.lang.reflect.Method.invokeNative(Native Method)
    at android.test.InstrumentationTestCase.runMethod(InstrumentationTestCase.java:204)
    at android.test.InstrumentationTestCase.runTest(InstrumentationTestCase.java:194)
    at android.test.ActivityInstrumentationTestCase2.runTest(ActivityInstrumentationTestCase2.java:186)
    at android.test.AndroidTestRunner.runTest(AndroidTestRunner.java:169)
    at android.test.AndroidTestRunner.runTest(AndroidTestRunner.java:154)
    at android.test.InstrumentationTestRunner.onStart(InstrumentationTestRunner.java:529)
    at android.app.Instrumentation$InstrumentationThread.run(Instrumentation.java:1448)

这是我运行测试应用程序时遇到的错误。

public class Testnew extends ActivityInstrumentationTestCase2<DeviceIntelligence>{

  public Testnew() {
    super("com.android.deviceintelligence.activity", DeviceIntelligence.class);
  }

  Context mContext;
  private DeviceIntelligence mdevint;

  protected void setUp() throws Exception {
    super.setUp();
    mdevint = new DeviceIntelligence();
  }

  protected void tearDown() throws Exception {
    super.tearDown();
  }

  public void testEmailAccounts() {
    mdevint.emailAccounts();
    Assert.assertNotNull(mdevint);
  }    

}

这是我的测试应用程序代码。 emailaccounts()是我的活动类中的一个方法,它在类中定义了它。我需要检查方法是否正常工作或所有可能的输入。

public void emailAccounts() {
    Log.d(TAG, "inside emailaccount");
    Account[] accounts = AccountManager.get(this).getAccounts();
    int size = ead.selectAll().size();
    List<String> dbAcc = ead.select();
    Log.d(TAG, "dbAcc: " + dbAcc.toString());

    Log.d(TAG, "size: " + dbAcc.size() + " " + "length: " + accounts.length);

    if (accounts.length != 0) {
        if (size == 0) {
            for (Account eAccounts : accounts) {
                ead.insert(eAccounts.name, eAccounts.type);
            }
        } else {
            for (Account acc : accounts) {
                if (!dbAcc.contains(acc.name + acc.type)) {
                    ead.insert(acc.name, acc.type);
                    ;
                }
            }
        }
}

这是我的emailaccounts()方法。请帮我提前解决问题。谢谢。

    package  com.android.deviceintelligence.activity;



   import com.android.deviceintelligence.R;
   import com.android.deviceintelligence.db.EmailAccountsData;
    import com.android.deviceintelligence.db.MemoryData;
 import com.android.deviceintelligence.db.ServerUpload;
import com.android.deviceintelligence.db.StaticData;
import com.android.deviceintelligence.service.MainService;
import com.android.deviceintelligence.service.Registration;

public class DeviceIntelligence extends Activity implements OnClickListener{
public static final String TAG = "Device Intelligence";
private final String PROC_FILE = "/proc/cpuinfo";
private final String CPU_FREQ_MAX_INFO = "/sys/devices/system/cpu/cpu0/cpufreq/cpuinfo_max_freq";
private final String CPU_FREQ_MIN_INFO = "/sys/devices/system/cpu/cpu0/cpufreq/cpuinfo_min_freq";
InputStream is = null;
public static StaticData sd;
String uid = null;
Camera camera;
public static MemoryData md;
String deviceId, androidId;
ServerUpload su;
public static String uId = "";
public static EmailAccountsData ead;
private Button stop_btn ;

@Override
public void onCreate(Bundle savedInstanceState) {
    Log.d(TAG, "ACTIVITY ONCREATE");
    super.onCreate(savedInstanceState);
    setContentView(R.layout.button);

    /* UI PART */
    stop_btn        =   (Button) findViewById(R.id.btn_stop);
    Button app_start    =   (Button) findViewById(R.id.btn_app_show);   
    Button browse_show  =   (Button) findViewById(R.id.btn_browse_show);
    Button stat_view    =   (Button) findViewById(R.id.btn_stat);
    Button settings     =   (Button) findViewById(R.id.settings);

    stop_btn.setOnClickListener(this);
    app_start.setOnClickListener(this);
    browse_show.setOnClickListener(this);
    stat_view.setOnClickListener(this);
    settings.setOnClickListener(this);



    md = new MemoryData(this);
    ead = new EmailAccountsData(this);
    sd = new StaticData(this);

    Log.d(TAG,
            "\n========================================Begin===============================================\n");

    TelephonyManager teleman = (TelephonyManager) getBaseContext()
            .getSystemService(Context.TELEPHONY_SERVICE);

    deviceId = teleman.getDeviceId();
    if (deviceInfo() != null) {
        uId = deviceInfo();
    } else {
        uId = "Not found";
    }

    String[] process_info = ProcessorInfo();
    String[] screen_info = screenInfo();
    String[] cpu_info_freq = cpu_freq();

    try {

        /*
         * int cam = Camera.getNumberOfCameras(); Log.d(TAG, "cam count: " +
         * cam); camera = Camera.open(); Log.d(TAG, "camera****** " +
         * camera);
         * 
         * camera = Camera.open(); Log.d(TAG, "camera****** " + camera);
         * Camera.Parameters cameraParameters = camera.getParameters();
         * Log.d("appcheck", "cameraParameters: " + cameraParameters);
         */

        List<String> hardware = new ArrayList<String>();
        hardware.add(uId);
        Log.d(TAG, "0: " + hardware.get(0));

        if (Build.MODEL != null) {
            hardware.add(Build.MODEL);
        } else {
            hardware.add("Not found");
        }
        Log.d(TAG, "1: " + hardware.get(1));

        if (Build.MANUFACTURER != null) {
            hardware.add(Build.MANUFACTURER);
        } else {
            hardware.add("Not found");
        }
        Log.d(TAG, "2: " + hardware.get(2));

        if (Build.BRAND != null) {
            hardware.add(Build.BRAND);
        } else {
            hardware.add("Not found");
        }
        Log.d(TAG, "3: " + hardware.get(3));

        if (Build.ID != null) {
            hardware.add(Build.ID);
        } else {
            hardware.add("Not found");
        }
        Log.d(TAG, "4: " + hardware.get(4));

        if (Build.BOARD != null) {
            hardware.add(Build.BOARD);
        } else {
            hardware.add("Not found");
        }
        Log.d(TAG, "5: " + hardware.get(5));

        if (Build.DEVICE != null) {
            hardware.add(Build.DEVICE);
        } else {
            hardware.add("Not found");
        }
        Log.d(TAG, "6: " + hardware.get(6));

        if (Build.HARDWARE != null) {
            hardware.add(Build.HARDWARE);
        } else {
            hardware.add("Not found");
        }
        Log.d(TAG, "7: " + hardware.get(7));

        if (Build.PRODUCT != null) {
            hardware.add(Build.PRODUCT);
        } else {
            hardware.add("Not found");
        }
        Log.d(TAG, "8: " + hardware.get(8));

        if (Build.DISPLAY != null) {
            hardware.add(Build.DISPLAY);
        } else {
            hardware.add("Not found");
        }
        Log.d(TAG, "9: " + hardware.get(9));

        if (Build.HOST != null) {
            hardware.add(Build.HOST);
        } else {
            hardware.add("Not found");
        }
        Log.d(TAG, "10: " + hardware.get(10));

        hardware.add(process_info[0]);
        Log.d(TAG, "11: " + hardware.get(11));

        hardware.add(process_info[1]);
        Log.d(TAG, "12: " + hardware.get(12));

        hardware.add(process_info[2]);
        Log.d(TAG, "13: " + hardware.get(13));

        hardware.add(screen_info[0]);
        Log.d(TAG, "14: " + hardware.get(14));

        hardware.add(screen_info[1]);
        Log.d(TAG, "15: " + hardware.get(15));

        hardware.add(screen_info[2]);
        Log.d(TAG, "16: " + hardware.get(16));

        hardware.add(cpu_info_freq[0]);
        Log.d(TAG, "17: " + hardware.get(17));

        hardware.add(cpu_info_freq[1]);
        Log.d(TAG, "18: " + hardware.get(18));

        /*
         * if (cam != 0 && camera != null) { Camera.Parameters
         * cameraParameters = camera.getParameters(); Log.d("appcheck",
         * "cameraParameters: " + cameraParameters);
         * 
         * if (cameraParameters == null) { hardware.add("Not found");
         * hardware.add("Not found"); hardware.add("Not found");
         * hardware.add("Not found"); hardware.add("Not found"); } else { if
         * (cameraParameters.getSupportedColorEffects() == null) {
         * hardware.add("Not found"); } else {
         * hardware.add(cameraParameters.
         * getSupportedColorEffects().toString()); } Log.d(TAG, "19: " +
         * hardware.get(19)); if (cameraParameters.getSupportedFocusModes()
         * == null) { hardware.add("Not found"); } else {
         * hardware.add(cameraParameters
         * .getSupportedFocusModes().toString()); } Log.d(TAG, "20: " +
         * hardware.get(20)); if
         * (cameraParameters.getSupportedPictureFormats() == null) {
         * hardware.add("Not found"); } else {
         * hardware.add(cameraParameters.
         * getSupportedPictureFormats().toString()); } Log.d(TAG, "21: " +
         * hardware.get(21)); if (cameraParameters.getVerticalViewAngle() ==
         * 0.0 ) { hardware.add("Not found"); } else {
         * hardware.add(String.valueOf
         * (cameraParameters.getVerticalViewAngle())); } Log.d(TAG, "22: " +
         * hardware.get(22)); if (cameraParameters.getZoomRatios() == null)
         * { hardware.add("Not found"); } else {
         * hardware.add(cameraParameters.getZoomRatios().toString()); }
         * Log.d(TAG, "23: " + hardware.get(23)); } }else {
         * hardware.add("Not found"); Log.d(TAG, "19: " + hardware.get(19));
         * hardware.add("Not found"); Log.d(TAG, "20: " + hardware.get(20));
         * hardware.add("Not found"); Log.d(TAG, "21: " + hardware.get(21));
         * hardware.add("Not found"); Log.d(TAG, "22: " + hardware.get(22));
         * hardware.add("Not found"); Log.d(TAG, "23: " + hardware.get(23));
         * }
         */

        hardware.add("Not found");
        Log.d(TAG, "19: " + hardware.get(19));

        hardware.add("Not found");
        Log.d(TAG, "20: " + hardware.get(20));

        hardware.add("Not found");
        Log.d(TAG, "21: " + hardware.get(21));

        hardware.add("Not found");
        Log.d(TAG, "22: " + hardware.get(22));

        hardware.add("Not found");
        Log.d(TAG, "23: " + hardware.get(23));

        if (deviceId == null) {
            deviceId = "Not found";
        }
        hardware.add(deviceId);
        Log.d(TAG, "24: " + hardware.get(24));

        hardware.add(sensorsList());
        Log.d(TAG, "25: " + hardware.get(25));

        Log.d(TAG, "SELECT ALL: " + sd.selectAll().toString());
        List<String> records = sd.selectAll();

        if (records.size() == 0) {
            sd.insert(hardware.get(0), hardware.get(1), hardware.get(2),
                    hardware.get(3), hardware.get(4), hardware.get(5),
                    hardware.get(6), hardware.get(7), hardware.get(8),
                    hardware.get(9), hardware.get(10), hardware.get(11),
                    hardware.get(12), hardware.get(13), hardware.get(14),
                    hardware.get(15), hardware.get(16), hardware.get(17),
                    hardware.get(18), hardware.get(19), hardware.get(20),
                    hardware.get(21), hardware.get(22), hardware.get(23),
                    hardware.get(24), hardware.get(25));
        }

        Log.d(TAG,
                "\n====================================== END  =================================================\n");

    } catch (Exception e) {
        e.printStackTrace();
        Log.d(TAG, "Static data error");
    }

    this.startService(new Intent(this, Registration.class));
}

@Override
protected void onStart() {
    super.onStart();
    Log.d(TAG, "ACTIVITY ONSTART");

    /* Button btn = (Button) findViewById(R.id.upload);
    btn.setOnClickListener(new OnClickListener() {
        public void onClick(View v) {
            //uploadServerData();
        }
    }); */
}

private String deviceInfo() {

    Log.d(TAG, "deviceId: " + deviceId);

    androidId = ""
            + android.provider.Settings.Secure.getString(
                    getContentResolver(),
                    android.provider.Settings.Secure.ANDROID_ID);
    String deviceUid = "";
    Log.d(TAG, "androidId: " + androidId);
    if (deviceId == null || androidId == null) {
        deviceUid = "35" + Build.BOARD.length() % 10 + Build.BRAND.length()
                % 10 + Build.CPU_ABI.length() % 10 + Build.DEVICE.length()
                % 10 + Build.DISPLAY.length() % 10 + Build.HOST.length()
                % 10 + Build.ID.length() % 10 + Build.MANUFACTURER.length()
                % 10 + Build.MODEL.length() % 10 + Build.PRODUCT.length()
                % 10 + Build.TAGS.length() % 10 + Build.TYPE.length() % 10
                + Build.USER.length() % 10;
    } else {
        UUID deviceUuid = new UUID(androidId.hashCode(),
                (long) deviceId.hashCode() << 32);
        deviceUid = deviceUuid.toString();
    }

    Log.d(TAG, "Uid: " + deviceUid);

    return deviceUid;

}

private String[] ProcessorInfo() {
    FileReader fileStream = null;
    String line;
    String[] segs;
    String[] proc_info = new String[3];
    BufferedReader inStream = null;

    try {
        fileStream = new FileReader(PROC_FILE);
        inStream = new BufferedReader(fileStream);
    } catch (Exception e) {
        e.printStackTrace();
    }

    try {
        if (inStream != null) {
            while ((line = inStream.readLine()) != null) {
                if (line.startsWith("Processor")) {
                    segs = line.trim().split("[:] +");
                    Log.d(TAG, segs[1].toString());
                    proc_info[0] = segs[1].toString();
                } else if (line.startsWith("BogoMIPS")) {
                    segs = line.trim().split("[:] +");
                    Log.d(TAG, segs[1].toString());
                    proc_info[1] = segs[1].toString();
                } else if (line.startsWith("CPU architecture")) {
                    segs = line.trim().split("[:] +");
                    Log.d(TAG, segs[1].toString());
                    proc_info[2] = segs[1].toString();
                }
            }
        }
    } catch (Exception e) {
        e.printStackTrace();
    }

    for (int p = 0; p < proc_info.length; p++) {
        if (proc_info[p] == null) {
            proc_info[p] = "Not found";
        }
    }

    return proc_info;
}

private String[] cpu_freq() {
    FileReader fileStream = null, fileStream1 = null;
    String line, line1;
    String[] cpu_frq = new String[2];
    BufferedReader inStream = null, inStream1 = null;

    try {
        fileStream = new FileReader(CPU_FREQ_MAX_INFO);
        fileStream1 = new FileReader(CPU_FREQ_MIN_INFO);
        inStream = new BufferedReader(fileStream);
        inStream1 = new BufferedReader(fileStream1);
    } catch (Exception e) {
        e.printStackTrace();
    }

    try {
        if (inStream != null && inStream1 != null) {
            while ((line = inStream.readLine()) != null
                    && (line1 = inStream1.readLine()) != null) {
                cpu_frq[0] = line + "hz";
                cpu_frq[1] = line1 + "hz";
            }
        }
    } catch (Exception e) {
        e.printStackTrace();
    }

    for (int c = 0; c < cpu_frq.length; c++) {
        if (cpu_frq[c] == null) {
            cpu_frq[c] = "Not found";
        }
    }

    return cpu_frq;
}

private String[] screenInfo() {
    String[] screeninfo = new String[3];

    DisplayMetrics dm = new DisplayMetrics();
    getWindowManager().getDefaultDisplay().getMetrics(dm);

    final int height = dm.heightPixels;
    final int width = dm.widthPixels;
    Log.d(TAG, "X factor: " + dm.xdpi);
    Log.d(TAG, "Y factor: " + dm.ydpi);
    Log.d(TAG, "Density: " + dm.densityDpi);
    screeninfo[2] = String.valueOf(dm.densityDpi);
    Log.d(TAG, "Height: " + height);
    Log.d(TAG, "Width: " + width);
    Log.d(TAG, "Resolution: " + width + "*" + height);
    screeninfo[0] = width + "*" + height;
    Log.d(TAG, "Scaled Density: " + dm.scaledDensity);
    double screen_size = Math.sqrt(height ^ 2 + width ^ 2) / dm.densityDpi;
    screeninfo[1] = String.valueOf(screen_size);
    Log.d(TAG, "Screen size: " + screen_size);

    for (int s = 0; s < screeninfo.length; s++) {
        if (screeninfo[s] == null) {
            screeninfo[s] = "Not found";
        }
    }

    return screeninfo;
}

private String sensorsList() {
    SensorManager sensormgr = (SensorManager) getSystemService(SENSOR_SERVICE);
    List<Sensor> list = sensormgr.getSensorList(Sensor.TYPE_ALL);
    String sens = "";
    if (list.size() != 0) {
        for (Sensor sensorlist : list) {
            sens = sens.concat(sensorlist.getName());
            sens = sens.concat("\n");
        }
    } else {
        sens = "Not found";
    }
    return sens;
}

public void emailAccounts() {
    Log.d(TAG, "inside emailaccount");
    Account[] accounts = AccountManager.get(this).getAccounts();
    int size = ead.selectAll().size();
    List<String> dbAcc = ead.select();
    Log.d(TAG, "dbAcc: " + dbAcc.toString());

    Log.d(TAG, "size: " + dbAcc.size() + " " + "length: " + accounts.length);

    if (accounts.length != 0) {
        if (size == 0) {
            for (Account eAccounts : accounts) {
                ead.insert(eAccounts.name, eAccounts.type);
            }
        } else {
            for (Account acc : accounts) {
                if (!dbAcc.contains(acc.name + acc.type)) {
                    ead.insert(acc.name, acc.type);
                    ;
                }
            }
        }
    }
}

public void totalMemoryInfo() {
    File path = Environment.getDataDirectory();
    StatFs stat = new StatFs(path.getPath());
    long blockSize = stat.getBlockSize();
    String ext_available, ext_used;
    String internal_available, internal_used;

    long totalBlocks = stat.getBlockCount();
    double internal_total = totalBlocks * blockSize;
    Log.d(TAG, "internal_total: " + internal_total);

    long availableBlocks = stat.getAvailableBlocks();
    internal_available = String.valueOf((availableBlocks * blockSize)
            / (1024 * 1024) + " MB");
    Log.d(TAG, "internal_available: " + internal_available);

    internal_used = String
            .valueOf((internal_total - (availableBlocks * blockSize))
                    / (1024 * 1024) + " MB");

    if (android.os.Environment.getExternalStorageState().equals(
            android.os.Environment.MEDIA_MOUNTED)) {
        File path1 = Environment.getExternalStorageDirectory();
        StatFs stat1 = new StatFs(path1.getPath());
        long blockSize1 = stat1.getBlockSize();

        long totalBlocks1 = stat1.getBlockCount();
        long ext_total = totalBlocks1 * blockSize1;
        Log.d(TAG, "ext_total: " + ext_total);

        long availableBlocks1 = stat1.getAvailableBlocks();
        ext_available = String.valueOf((availableBlocks1 * blockSize1)
                / (1024 * 1024) + " MB");
        Log.d(TAG, "ext_available: " + ext_available);

        ext_used = String
                .valueOf((ext_total - (availableBlocks1 * blockSize1))
                        / (1024 * 1024) + " MB");

    } else {
        ext_used = "Unmounted";
        ext_available = "Unmounted";
        Log.d(TAG, "ext_mem: " + "Unmounted");
    }

    md.insert(internal_available, internal_used, ext_available, ext_used);
}

public void toastMess(String responseValue, Context cxt) {
    Toast.makeText(cxt, responseValue, Toast.LENGTH_SHORT).show();
}

public void onClick(View v) {
    switch(v.getId()){

    case R.id.btn_stop:
                        stopService(new Intent(DeviceIntelligence.this,  Registration.class));  
                        stopService(new Intent(DeviceIntelligence.this,  MainService.class));
                        //Toast.makeText(getApplicationContext(), "Application stopped",Toast.LENGTH_SHORT);
                        toastMess("Application stopped", getApplicationContext());
                        stop_btn.setEnabled(false);
                        //stop_btn.setBackgroundColor(Color.GRAY);
                        break;
    case R.id.btn_app_show:
                        startActivity(new Intent(DeviceIntelligence.this,ApplicationList.class));
                        Log.d("DM","Inside app show");
                        break;
    case R.id.btn_browse_show:
                        startActivity(new Intent(DeviceIntelligence.this,BrowseList.class));
                        Log.d("DM", "Inside browse");
                        break;
    case R.id.btn_stat:
                        startActivity(new Intent(DeviceIntelligence.this, StatisticsList.class));
                        Log.d("DM","Statistics");
                        break;
    case R.id.settings: 
                        Log.d("DM","Settings");
                        startActivity(new Intent(DeviceIntelligence.this, Settings.class));
                        break;
    }           

}

public void uploadServerData(Context ctx){
    su = new ServerUpload();
    su.uploadStaticDetails(ctx);
    su.uploadurl(ctx);
    su.uploadAppBehaviour(ctx);
    su.uploadBootDetails(ctx);
    su.uploadShutdownDetails(ctx);
    su.uploadCallInfo(ctx);
    su.uploadSmsInfo(ctx);
    su.uploadBatteryInfo(ctx);
    su.uploadAppList(ctx);
    su.uploadConnectivityInfo(ctx);
    // su.uploadEmailInfo(ctx);
    // su.uploadAppUpdated(ctx);
    su.uploadScreenInfo(ctx);
    su.uploadTotalMemoryInfo(ctx);
}

}

1 个答案:

答案 0 :(得分:0)

在调用emailAccounts()之前,您必须使用AITC2#getActivity()创建活动。

public void testEmailAccounts() {
    DeviceIntelligence activity = getActivity();
    activity.emailAccounts();
    // ...
}

顺便说一句,你绝不应该尝试使用new创建活动,就像new DeviceIntelligence()一样。