我有以下情况。
我的活动有一个依赖于Serializable Object的片段。这是我的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
始终为空。我认为这应该很简单。我失踪了什么?
答案 0 :(得分:25)
您可以定义以这种方式使用的意图
function sub_form() {
document.getElementById('popWindow').style.display = 'none';
var modi_Game = document.getElementById("modi_Game");
modi_Game.action = "yourlink.html";
$("#modi_Game").submit();
}
$(document).ready(function () {
$("#modi_Game").submit(function (event) {
alert("Stoping the form submitting");
event.preventDefault();
document.getElementById('popWindow_ok').style.display = 'block';
});
});
答案 1 :(得分:14)
您可以覆盖ActivityTestRule.getActivityIntent()方法并返回所需的意图:
@Rule
public ActivityTestRule<MyActivity> mActivityRule =
new ActivityTestRule<MyActivity>(MyActivity.class){
@Override
protected Intent getActivityIntent() {
Intent intent = new Intent();
intent.putExtra("myobj", myObj);
return intent;
}
};
答案 2 :(得分:0)
看起来你实际上并没有在任何地方开始活动。
尝试在testName()的第一行调用getActivity()
。
这将启动您传递给超级构造函数的活动。