getActivity()在我的ActivityInstrumentationTestCase2类中返回null

时间:2015-11-16 02:58:12

标签: android testing android-activity nullpointerexception get

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

这是实际的Test类:

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

这是清单文件和gradle文件,如果它们有所不同:

清单文件:

<?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>

摇篮:

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

1 个答案:

答案 0 :(得分:9)

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

有两种方法:

  1. 继续使用ActivityInstrumentationTestCase2来测试此Activity,从代码中删除所有@Before @Test注释,测试用例应该没有问题。
  2. 不要将ActivityInstrumentationTestCase2子类化为使用AndroidJUnitRunner,并通过设置活动测试规则来设置活动
  3.   

    JUnit4下的测试用例:

    public class DraftsActivityTest2 {
    
    @Rule
    public ActivityTestRule<DraftsActivity> mActivityRule = new ActivityTestRule<>(
            DraftsActivity.class);
    
    @Before
    public void setUp(){
        DraftsActivity activity = mActivityRule.getActivity();
        ...}
    }