今天学习了单元测试框架,Robolectric。初步感觉,可能我测试的少,没有感觉Robolectric能有多大的帮助。虽然可以帮助创建activity。可以模拟点击事件。可是有什么呢。

好吧,讲下使用:

参看:

http://robolectric.org/extending/

https://github.com/robolectric/robolectric

1.这个框架是要配合junit使用的。所以:

    testCompile 'junit:junit:4.12'
testCompile "org.robolectric:robolectric:3.1"

2.编写测试代码:

package cebactivity.chinaceb.com.myapplication;

import android.content.Intent;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.robolectric.Robolectric;
import org.robolectric.RobolectricGradleTestRunner;
import org.robolectric.Shadows;
import org.robolectric.annotation.Config;
import org.robolectric.shadows.ShadowActivity; import static junit.framework.TestCase.assertNotNull;
import static org.junit.Assert.assertEquals; /**
* Created by Administrator on 2016/6/26.
*/
@RunWith(RobolectricGradleTestRunner.class)
@Config(constants = BuildConfig.class, sdk = 19)
public class testmain {
@Test
public void testMainActivity() {
MainActivity mainActivity = Robolectric.setupActivity(MainActivity.class);
mainActivity.findViewById(R.id.bt).performClick(); Intent expectedIntent = new Intent(mainActivity, SecondActivity.class);
ShadowActivity shadowActivity = Shadows.shadowOf(mainActivity);
Intent actualIntent = shadowActivity.getNextStartedActivity();
assertEquals(expectedIntent, actualIntent);
} @Test
public void testActivity() {
MainActivity sampleActivity = Robolectric.setupActivity(MainActivity.class);
assertNotNull(sampleActivity);
assertEquals(sampleActivity.getClass().getName(), "cebactivity.chinaceb.com.myapplication.MainActivity");
}
}

第一个测试老是通不过,妈的,明明是同一个,偏偏不让我过。好吧,不许吐槽。

04-23 07:51