本文共 2041 字,大约阅读时间需要 6 分钟。
在src中有三个包,分别是:test、androidTest 和java
test:是测试不涉及Activity,UI组件的纯Java方法。 直接在电脑上直接测试。 androidTest:涉及UI,Android组件的都在该路径下测试。 需要连接真机,或者模拟器进行测试。 java:项目代码在moudle中的build.gradle文件下依赖
testCompile "org.robolectric:robolectric:3.6.1"
public class MainActivity extends AppCompatActivity { private static final String TAG = "MainActivity"; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); ButterKnife.inject(this); } @OnClick(R.id.btn_login) public void login(){ Log.e(TAG, "login: 登录"); Toast.makeText(this, "登录", Toast.LENGTH_SHORT).show(); } @OnClick(R.id.btn_open) public void open(){ Intent intent = new Intent(MainActivity.this, LoginActivity.class); startActivity(intent); }}
/** * @author mazaiting * @date 2017/12/26 */@RunWith(RobolectricTestRunner.class)@Config(constants = BuildConfig.class, sdk = 21)public class MainActivityTest { @Before public void before(){ Logger.error("start"); } @Test public void clickLoginBtn(){ MainActivity activity = Robolectric.setupActivity(MainActivity.class); activity.findViewById(R.id.btn_login).performClick(); Logger.error(ShadowToast.getTextOfLatestToast()); } @Test public void clickOpenBtn(){ MainActivity activity = Robolectric.setupActivity(MainActivity.class); activity.findViewById(R.id.btn_open).performClick(); Intent expectedIntent = new Intent(activity, LoginActivity.class); Intent actual = ShadowApplication.getInstance().getNextStartedActivity(); Logger.debug(expectedIntent.getComponent().toString()); Logger.debug(actual.getComponent().toString()); Assert.assertEquals(expectedIntent.getComponent(), actual.getComponent()); } @After public void after(){ Logger.error("after"); }}
转载地址:http://gblzl.baihongyu.com/