The app test started with Robolectric

image.png
  1. Set up android dev env
Android Studio 3.0+
  1. Building with gradle
android {
  testOptions {
    unitTests {
      includeAndroidResources = true
    }
  }
} 
dependencies {
testImplementation "org.robolectric:robolectric:3.6.1"
}
  1. New test file in app/src/test.
@RunWith(RobolectricTestRunner.class)
public class
SimpleRobolectricTest {
}

If you use it in app/src/androidTest, it will can not resolve symbol "RobolectricTestRunner".

  1. Give you an example test
  • For example I want to test a user clicks on a back icon in MyMessageActivity, the app launches the MyHorizontalCoordinatorNtbActivity
public class MessageActivity extends SwipeBackActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_message);
        initView();
    }

    private void initView() {
        ImageView iv_back = (ImageView) findViewById(R.id.iv_back);
        iv_back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(MessageActivity.this, MyHorizontalCoordinatorNtbActivity.class);
                startActivity(intent);
                finish();
            }
        });
    }
}
  • In order to test this, we can check that when a user clicks on the “back” icon, we start the correct intent. Because Robolectric is a unit testing framework, the MyHorizontalCoordinatorNtbActivity will not actually be started, but we can check that the MyMessageActivity fired the correct intent:
import android.content.Intent;

import com.koko.prototype.alert.activity.MessageActivity;
import com.koko.prototype.alert.activity.MyHorizontalCoordinatorNtbActivity;
import com.koko.prototype.alert.dao.Message;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.robolectric.Robolectric;
import org.robolectric.RobolectricTestRunner;
import org.robolectric.shadows.ShadowApplication;

import static junit.framework.Assert.assertEquals;

/**
 * Created by emily on 2018/1/17
 */

@RunWith(RobolectricTestRunner.class)
public class
SimpleRobolectricTest {

    @Test
    public void clickingLogin_shouldStartLoginActivity(){
        MessageActivity activity = Robolectric.setupActivity(MessageActivity.class);
        activity.findViewById(R.id.iv_back).performClick();

        Intent expectedIntent = new Intent(activity, MyHorizontalCoordinatorNtbActivity.class);
        Intent actual = ShadowApplication.getInstance().getNextStartedActivity();
        assertEquals(expectedIntent.getComponent(), actual.getComponent());
    }
}

  • And then click run
image.png
  • Operation result
image.png
  1. Robolectric
    Robolectric is a unit test framework that de-fangs the Android SDK jar so you can test-drive the development of your Android app. Tests run inside the JVM on your workstation in seconds.

  2. Some Issue

  • Some methods can not be resolved
    solution:
    Alt+Enter (Mac)
image.png

image.png
  1. More about robolectric
    [1] test textView
TextView mTextView =(TextView) activity.findViewById(R.id.tv_title);
assertThat(mTextView.getText().toString()).isEqualTo("Title");

[2] test activity lifecycle

Activity activity = Robolectric.buildActivity(MessageActivity.class).create().start().resume().visible().get();

[3] test restore saved instance state

Bundle savedInstanceState = new Bundle();
       Activity activity = Robolectric.buildActivity(MessageActivity.class).create().restoreInstanceState(savedInstanceState).get();

[4] using qualified resources
resource qualifiers allow you to change how your resources are loaded based on such factors as the language on the device, to the screen size, to whether it is day or night.
for run tests in different resource qualified contexts.

    @Test
    @Config(qualifiers="en-port")
    public void shouldUseEnglishAndPortraitResources(){
        final Context context = RuntimeEnvironment.application;
        assertThat(context.getString(R.string.not_overridden)).isEqualTo("Not Overridden");
        assertThat(context.getString(R.string.overridden)).isEqualTo("English qualified value");
        assertThat(context.getString(R.string.overridden_twice)).isEqualTo("English portrait qualified value");
    }

[5] set application

    @Config(application = MyApplication.class)
    public void getSandwich_shouldReturnHamSandwich() {
    }

[6] set resource path

   @Config(resourceDir = "other/build/path/ham-sandwich/res")
    public void getSandwich_show() {
    }
  1. Shadow classes
    it's created for extending the behavior of android os's class.
import android.view.ViewGroup;

import org.robolectric.annotation.Implementation;
import org.robolectric.annotation.Implements;
import org.robolectric.shadows.ShadowView;

/**
 * Created by emily on 2018/1/17
 */

@Implements(ViewGroup.class)
public class ShadowExample extends ShadowView{
    
    @Implementation
    public void setImageResource(int resId){
    }
    
    public ShadowExample(){
        
    }
}
  1. Thank you
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末,一起剝皮案震驚了整個濱河市梭稚,隨后出現(xiàn)的幾起案子颖低,更是在濱河造成了極大的恐慌,老刑警劉巖弧烤,帶你破解...
    沈念sama閱讀 217,084評論 6 503
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件忱屑,死亡現(xiàn)場離奇詭異,居然都是意外死亡,警方通過查閱死者的電腦和手機莺戒,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 92,623評論 3 392
  • 文/潘曉璐 我一進店門伴嗡,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人从铲,你說我怎么就攤上這事瘪校。” “怎么了名段?”我有些...
    開封第一講書人閱讀 163,450評論 0 353
  • 文/不壞的土叔 我叫張陵阱扬,是天一觀的道長。 經(jīng)常有香客問我伸辟,道長麻惶,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 58,322評論 1 293
  • 正文 為了忘掉前任信夫,我火速辦了婚禮窃蹋,結(jié)果婚禮上,老公的妹妹穿的比我還像新娘静稻。我一直安慰自己脐彩,他們只是感情好,可當(dāng)我...
    茶點故事閱讀 67,370評論 6 390
  • 文/花漫 我一把揭開白布姊扔。 她就那樣靜靜地躺著,像睡著了一般梅誓。 火紅的嫁衣襯著肌膚如雪恰梢。 梳的紋絲不亂的頭發(fā)上,一...
    開封第一講書人閱讀 51,274評論 1 300
  • 那天梗掰,我揣著相機與錄音嵌言,去河邊找鬼。 笑死及穗,一個胖子當(dāng)著我的面吹牛摧茴,可吹牛的內(nèi)容都是我干的。 我是一名探鬼主播埂陆,決...
    沈念sama閱讀 40,126評論 3 418
  • 文/蒼蘭香墨 我猛地睜開眼苛白,長吁一口氣:“原來是場噩夢啊……” “哼!你這毒婦竟也來了焚虱?” 一聲冷哼從身側(cè)響起购裙,我...
    開封第一講書人閱讀 38,980評論 0 275
  • 序言:老撾萬榮一對情侶失蹤,失蹤者是張志新(化名)和其女友劉穎鹃栽,沒想到半個月后躏率,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體,經(jīng)...
    沈念sama閱讀 45,414評論 1 313
  • 正文 獨居荒郊野嶺守林人離奇死亡,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點故事閱讀 37,599評論 3 334
  • 正文 我和宋清朗相戀三年薇芝,在試婚紗的時候發(fā)現(xiàn)自己被綠了蓬抄。 大學(xué)時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
    茶點故事閱讀 39,773評論 1 348
  • 序言:一個原本活蹦亂跳的男人離奇死亡夯到,死狀恐怖嚷缭,靈堂內(nèi)的尸體忽然破棺而出,到底是詐尸還是另有隱情黄娘,我是刑警寧澤峭状,帶...
    沈念sama閱讀 35,470評論 5 344
  • 正文 年R本政府宣布,位于F島的核電站逼争,受9級特大地震影響优床,放射性物質(zhì)發(fā)生泄漏。R本人自食惡果不足惜誓焦,卻給世界環(huán)境...
    茶點故事閱讀 41,080評論 3 327
  • 文/蒙蒙 一胆敞、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧杂伟,春花似錦移层、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,713評論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至越平,卻和暖如春频蛔,著一層夾襖步出監(jiān)牢的瞬間,已是汗流浹背秦叛。 一陣腳步聲響...
    開封第一講書人閱讀 32,852評論 1 269
  • 我被黑心中介騙來泰國打工晦溪, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留,地道東北人挣跋。 一個月前我還...
    沈念sama閱讀 47,865評論 2 370
  • 正文 我出身青樓三圆,卻偏偏與公主長得像,于是被迫代替她去往敵國和親避咆。 傳聞我的和親對象是個殘疾皇子舟肉,可洞房花燭夜當(dāng)晚...
    茶點故事閱讀 44,689評論 2 354