我有以下情况。
我的 Activity 有一个依赖于可序列化对象的 fragment 。这是我的 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 测试中,我根本无法在创建 Activity 之前将 Intent 传递给 Activity 。我以多种方式尝试了 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
在测试中始终为空。我认为这应该很简单。我错过了什么?
最佳答案
您可以通过这种方式定义要使用的 Intent
@RunWith(AndroidJUnit4.class)
public class MyActivityTestTest {
private MyObject myObj;
@Rule
// third parameter is set to false which means the activity is not started automatically
public ActivityTestRule<MyActivity> mActivityRule =
new ActivityTestRule<>(MyActivity.class, false, false);
@Test
public void testName() {
myObj = MyObject.mockObject();
Intent i = new Intent();
i.putExtra("myobj", myObj);
mActivityRule.launchActivity(i);
//...
}
}
关于android - 依赖于 Intent 的 Espresso startActivity,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31752303/