getActivity()在我的ActivityInstrumentationTestCase2类中返回一个空值 [英] getActivity() returns a null in my ActivityInstrumentationTestCase2 class

查看:110
本文介绍了getActivity()在我的ActivityInstrumentationTestCase2类中返回一个空值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我希望我的应用程序使用ActivityInstrumentationTestCase2在代码中执行以下测试。问题是getActivity()方法返回null。这会在包含getActivity()的行的正下方的行处产生NullPointerException。结果,测试无法运行。我不知道它为什么这样做。我已经尝试将@Before改为@Override,但问题仍然存在。



以下是实际的Test类:

  package com.example.guy.smsclassprojecttest; 

导入android.test.ActivityInstrumentationTestCase2;
导入android.test.suitebuilder.annotation.SmallTest;
导入android.widget.Button;
导入android.widget.EditText;

import com.example.guy.smsclassproject。*;

import org.junit。*;
import org.junit.Test;

import java.util.ArrayList;


public class DraftsActivityTest2 extends ActivityInstrumentationTestCase2< DraftsActivity>
{
private EditText searchText;
私人按钮searchButton;
private DraftsDatabase draftsDatabase;
ArrayList< MessageObject> messagesToBeDisplayed;
DraftsActivity测试人员;

public DraftsActivityTest2()
{
super(DraftsActivity.class);


$ b @Before
public void setUp()throws Exception
{

draftsDatabase = new DraftsDatabase();
MessageObject messageObject1 = new MessageObject(hi,5554,true);
MessageObject messageObject2 = new MessageObject(hi hi,5555554,true);
MessageObject messageObject3 = new MessageObject(sup,5435555554,true);
draftsDatabase.addMessage(messageObject1);
draftsDatabase.addMessage(messageObject2);
draftsDatabase.addMessage(messageObject3);
messagesToBeDisplayed = draftsDatabase.getAllTexts();
//这里是代码崩溃的地方
tester = getActivity();
messagesToBeDisplayed = tester.messagesToBeDisplayed;
searchText =(EditText)tester.findViewById(R.id.searchText);
searchButton =(Button)tester.findViewById(R.id.searchButton);
}

@Test
public void testSearch(){

searchText.setText(hi);
searchButton.performClick();
messagesToBeDisplayed = draftsDatabase.getMessagesByKey(searchText.getText()。toString());
Assert.assertEquals(Messages with the word hi,2,messagesToBeDisplayed.size());
Assert.assertTrue(false);


$ / code $


这里是清单文件和gradle文件,如果它们有所作为:

清单文件:

 <?xml version =1.0encoding =utf-8?> 
< manifest xmlns:android =http://schemas.android.com/apk/res/android
package =com.example.guy.smsclassproject>

< uses-sdk android:minSdkVersion =10/>
android:versionCode =1
android:versionName =1.0>
< uses-permission android:name =android.permission.SEND_SMS/>
< uses-permission android:name =android.permission.RECEIVE_SMS/>
<使用权限android:name =android.permission.READ_CONTACTS/>

<使用权限android:name =android.permission.WRITE_EXTERNAL_STORAGE/>
<使用权限android:name =android.permission.READ_PHONE_STATE/>
<使用权限android:name =android.permission.READ_EXTERNAL_STORAGE/>

$ b< application
android:allowBackup =true
android:icon =@ mipmap / ic_launcher
android:label =SMS
android:supportsRtl =true
android:theme =@ style / AppTheme>

<! - 主菜单 - >
< activity android:name =。MenuActivityandroid:label =SMS>
< intent-filter>

< category android:name =android.intent.category.LAUNCHER/>
< / intent-filter>
< / activity>

<! - 草稿 - >
< activity android:name =。DraftsActivity
android:label =草稿
android:windowSoftInputMode =adjustPan> <! - 停止键盘搞乱布局 - >
< / activity>

<! - 历史记录 - >
< activity
android:name =。HistoryActivity
android:label =最近文本
android:windowSoftInputMode =adjustPan> <! - 停止键盘搞乱布局 - >
< / activity>

<! - - 文字 - >
< activity
android:name =。TextingActivity
android:label =发短信
android:windowSoftInputMode =adjustPan> <! - 停止键盘搞乱布局 - >
< / activity>

< receiver android:name =。SmsReceiver>
< intent-filter>
< / intent-filter>
< / receiver>

< activity
android:name =。SingleTextActivity
android:label =Message> // http://stackoverflow.com/questions/2198410/如何更改Android中的活动标题 - Tian
< / activity>
< / application>

< / manifest>

Gradle:

  apply plugin:'com.android.application'

android {
compileSdkVersion 23
buildToolsVersion23.0.1

defaultConfig {
的minSdkVersion 15
targetSdkVersion 23
的versionCode 1个
的versionName 1.0
testApplicationId 'com.example.guy.smsclassprojecttest'


}
buildTypes {
释放{
minifyEnabled假
proguardFiles getDefaultProguardFile( 'proguard的-android.txt'), 'proguard-rules.pro'
}
}

testOptions {

unitTests.returnDefaultValues = true

}

defaultConfig
{
testInstrumentationRunnerandroid.support.test.runner.AndroidJUnitRunner
}
}


依赖关系{
编译fileTree(dir: 'libs',包括:[' * .jar'])
testCompile'junit:junit:4.12'
compile'c​​om.android.support:appcompat-v7:23.1.0'
compile'c​​om.android.support: design:23.1.0'
androidTestCompile'c​​om.android.support.test.espresso:espresso-core:2.0'
androidTestCompile'c​​om.android.support.test:testing-support-lib:0.1'
testCompile'junit:junit:4.12'
}


解决方案

如果您使用的是ActivityInstrumentationTestCase2,则不需要@Before,@Test注释。

有两种方法可以使用:


  1. 继续使用ActivityInstrumentationTestCase2来测试这个Activity,从你的代码中删除所有的@Before @Test注解,并且测试用例应该没有问题地运行。
  2. 不要继承ActivityInstrumentationTestCase2,而是使用AndroidJUnitRunner,并设置通过设置活动测试规则像这样




JUnit4下的测试用例:




  public class DraftsActivityTest2 {

@Rule
public ActivityTestRule< DraftsActivity> mActivityRule = new ActivityTestRule<>(
DraftsActivity.class);

@Before
public void setUp(){
DraftsActivity activity = mActivityRule.getActivity();
...}
}


I want my app to perform the following test in the code with ActivityInstrumentationTestCase2. The problem is the getActivity() method returns a null. This results in a NullPointerException at the line directly underneath the line that contains getActivity(). As a result, the test cannot run. I don't know why it is doing that. I have already tried changing @Before to @Override but the problem continues.

Here is the actual Test class:

package com.example.guy.smsclassprojecttest;

import android.test.ActivityInstrumentationTestCase2;
import android.test.suitebuilder.annotation.SmallTest;
import android.widget.Button;
import android.widget.EditText;

import com.example.guy.smsclassproject.*;

import org.junit.*;
import org.junit.Test;

import java.util.ArrayList;


public class DraftsActivityTest2 extends ActivityInstrumentationTestCase2<DraftsActivity>
{
    private EditText searchText;
    private Button searchButton;
    private DraftsDatabase draftsDatabase;
    ArrayList<MessageObject> messagesToBeDisplayed;
    DraftsActivity tester;

    public DraftsActivityTest2()
    {
        super(DraftsActivity.class);

    }

    @Before
    public void setUp() throws Exception
    {

        draftsDatabase = new DraftsDatabase();
        MessageObject messageObject1 = new MessageObject("hi", "5554", true);
        MessageObject messageObject2 = new MessageObject("hi hi", "5555554", true);
        MessageObject messageObject3 = new MessageObject("sup", "5435555554", true);
        draftsDatabase.addMessage(messageObject1);
        draftsDatabase.addMessage(messageObject2);
        draftsDatabase.addMessage(messageObject3);
        messagesToBeDisplayed = draftsDatabase.getAllTexts();
        //Here is where the code crashes
        tester = getActivity();
        messagesToBeDisplayed = tester.messagesToBeDisplayed;
        searchText = (EditText) tester.findViewById(R.id.searchText);
        searchButton = (Button) tester.findViewById(R.id.searchButton);
    }

    @Test
    public void testSearch() {

        searchText.setText("hi");
        searchButton.performClick();
        messagesToBeDisplayed = draftsDatabase.getMessagesByKey(searchText.getText().toString());
        Assert.assertEquals("Messages with the word hi", 2, messagesToBeDisplayed.size());
        Assert.assertTrue(false);
    }
}

Here is the manifest file and the gradle file if they make a difference:

Manifest File:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.guy.smsclassproject" >

    <uses-sdk android:minSdkVersion="10" />
    android:versionCode="1"
    android:versionName="1.0">
    <uses-permission android:name="android.permission.SEND_SMS" />
    <uses-permission android:name="android.permission.RECEIVE_SMS" />
    <uses-permission android:name="android.permission.READ_CONTACTS" />

    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
    <uses-permission android:name="android.permission.READ_PHONE_STATE" />
    <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />


    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="SMS"
        android:supportsRtl="true"
        android:theme="@style/AppTheme" >

        <!-- main menu -->
        <activity android:name=".MenuActivity" android:label="SMS">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>

        <!-- Drafts -->
        <activity android:name=".DraftsActivity"
            android:label="Drafts"
            android:windowSoftInputMode="adjustPan"> <!-- stops keyboard from messing up layout -->
        </activity>

        <!-- History -->
        <activity
            android:name=".HistoryActivity"
            android:label="Recent Texts"
            android:windowSoftInputMode="adjustPan"> <!-- stops keyboard from messing up layout -->
        </activity>

        <!-- Texts -->
        <activity
            android:name=".TextingActivity"
            android:label="Texting"
            android:windowSoftInputMode="adjustPan" > <!-- stops keyboard from messing up layout -->
        </activity>

        <receiver android:name=".SmsReceiver" >
            <intent-filter>
                <action android:name="android.provider.Telephony.SMS_RECEIVED" />
            </intent-filter>
        </receiver>

        <activity
            android:name=".SingleTextActivity"
            android:label="Message" >//http://stackoverflow.com/questions/2198410/how-to-change-title-of-activity-in-android--Tian
        </activity>
    </application>

</manifest>

Gradle:

apply plugin: 'com.android.application'

android {
    compileSdkVersion 23
    buildToolsVersion "23.0.1"

    defaultConfig {
        minSdkVersion 15
        targetSdkVersion 23
        versionCode 1
        versionName "1.0"
        testApplicationId 'com.example.guy.smsclassprojecttest'


    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }

    testOptions {

        unitTests.returnDefaultValues = true

    }

    defaultConfig
    {
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
    }
}


dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    testCompile 'junit:junit:4.12'
    compile 'com.android.support:appcompat-v7:23.1.0'
    compile 'com.android.support:design:23.1.0'
    androidTestCompile 'com.android.support.test.espresso:espresso-core:2.0'
    androidTestCompile 'com.android.support.test:testing-support-lib:0.1'
    testCompile 'junit:junit:4.12'
}

解决方案

If you are using ActivityInstrumentationTestCase2, you don't need the @Before, @Test annotations.

There are 2 ways to go:

  1. Continue to use ActivityInstrumentationTestCase2 to test this Activity, remove all the @Before @Test annotations from your code, and the test case should run without a problem.
  2. Don't subclass ActivityInstrumentationTestCase2, instead, to use AndroidJUnitRunner, and set the Activity by setting the activity test rule like this

Test case under JUnit4:

public class DraftsActivityTest2 {

@Rule
public ActivityTestRule<DraftsActivity> mActivityRule = new ActivityTestRule<>(
        DraftsActivity.class);

@Before
public void setUp(){
    DraftsActivity activity = mActivityRule.getActivity();
    ...}
}

这篇关于getActivity()在我的ActivityInstrumentationTestCase2类中返回一个空值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆