【发布时间】:2015-07-31 17:56:21
【问题描述】:
我有以下情况。
我的活动有一个依赖于可序列化对象的片段。这是我的 onCreate:
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
MyObject myObj = (MyObj) getIntent().getSerializableExtra("myobj");
if(myObj != null) {
FragmentManager manager = getSupportFragmentManager();
FragmentTransaction transaction = manager.beginTransaction();
transaction.add(R.id.container, MyFragment.newInstance(myObj));
transaction.commit();
}
}
但在我的 Espresso 测试中,我根本无法在创建活动之前将意图传递给活动。我以多种方式尝试了 setActivityIntent,但无法弄清楚如何使其工作。
这是我最后一次尝试:
import android.content.Intent;
import android.support.test.InstrumentationRegistry;
import android.support.test.espresso.Espresso;
import android.test.ActivityInstrumentationTestCase2;
import org.junit.Before;
import static android.support.test.espresso.assertion.ViewAssertions.matches;
import static android.support.test.espresso.matcher.ViewMatchers.withId;
import static android.support.test.espresso.matcher.ViewMatchers.withText;
public class MyActivityTest extends
ActivityInstrumentationTestCase2<MyActivity> {
private MyActivity activity;
private MyObject myObj;
public MyActivityTest() {
super(MyActivity.class);
}
@Before
protected void setUp() throws Exception {
super.setUp();
injectInstrumentation(InstrumentationRegistry.getInstrumentation());
myObj = MyObject.mockObject();
Intent i = new Intent();
i.putExtra("myobj", myObj);
setActivityIntent(i);
}
public void testName(){
Espresso.onView(withId(R.id.name)).check(matches(withText(myObj.getObjName())));
}
}
我搜索了很多,但没有任何效果。 MyObject 在测试中始终为空。我认为这应该很简单。我错过了什么?
【问题讨论】:
-
你得到什么错误信息?
-
你不需要@Before,因为这是 JUnit 3 测试而不是 JUnit 4 测试。
-
已解决,问题出在我的模拟...抱歉打扰了。
-
Kotlin 中的解决方案取自 here
标签: android testing android-intent android-espresso