我已经在我的Android应用程序上实现了MVP,我正在寻找创建测试脚本来测试基本行为功能。长话短说,有没有办法获得我创建的阴影对象的实例?
我希望能够告诉模拟模型对象在方法中返回什么,例如,当调用getGender()时,返回Male,但对于另一种方法,getGender()将返回Female。
我现在已经找到了它,但我很幸运,模型的设计。这是测试:
@RunWith(RobolectricTestRunner.class)
@Config(constants = BuildConfig.class, sdk = 22, shadows = { GenderPreferenceInteractorShaddow.class })
public class newPreferenceBehaviourTest {
@Test
public void clickingLogin_shouldStartLoginActivity() {
NewPreferenceMobileActivityTest activity = Robolectric.setupActivity(NewPreferenceMobileActivityTest.class);
activity.setGender(Gender.MALE);
activity.findViewById(R.id.femaleImageButton).performClick();
activity.findViewById(R.id.positiveButton).performClick();
}
}
模型构造函数将上下文作为构造,因此我可以创建一个测试活动,它扩展了我想要测试的活动。
public class NewPreferenceMobileActivityTest extends NewPreferenceMobileActivity {
public Gender getGender() {
return gender;
}
public void setGender(Gender gender) {
this.gender = gender;
}
private Gender gender;
}
这个新模型将包含我想要更改的值的getter和setter。在shadow对象的构造函数中,我可以将上下文转换为测试活动,然后模拟模型的getter可以返回我想要的内容:
@Implements(GenderPreferenceInteractor.class)
public class GenderPreferenceInteractorShaddow {
private NewPreferenceMobileActivityTest newPreferenceMobileActivityTest;
private GenderPreferenceMVP.onFinished onFinished;
public void __constructor__ (Context context) {
newPreferenceMobileActivityTest = (NewPreferenceMobileActivityTest) context;
}
@Implementation
public void saveGender(Gender gender) {
onFinished.onSaveSuccess(true);
}
@Implementation
public Gender getGender()
{
return newPreferenceMobileActivityTest.getGender();
}
}
编辑 - >不可能,但有一个解决方法。在GenderPreferenceInteractorShaddow类中,将引用传递回NewPreferenceMobileActivityTest类,我们引用该类。
public void __constructor__ (Context context) {
newPreferenceMobileActivityTest = (NewPreferenceMobileActivityTest) context;
newPreferenceMobileActivityTest.setGenderPreferenceInteractorShaddow(this);
}
public class NewPreferenceMobileActivityTest extends NewPreferenceMobileActivity {
private GenderPreferenceInteractorShaddow genderPreferenceInteractorShaddow;
public ladenzeile.android.newPreference.GenderPreferenceInteractorShaddow getGenderPreferenceInteractorShaddow() {
return genderPreferenceInteractorShaddow;
}
public void setGenderPreferenceInteractorShaddow(ladenzeile.android.newPreference.GenderPreferenceInteractorShaddow genderPreferenceInteractorShaddow) {
this.genderPreferenceInteractorShaddow = genderPreferenceInteractorShaddow;
这样做的缺点是您需要将Gender变量设置为默认值
答案 0 :(得分:2)
您可以像这样使用ShadowExtractor:
ThumbnailCard plCard = new ThumbnailCard()
{
Title = "I'm a thumbnail card",
Subtitle = "Pig Latin Wikipedia Page",
Images = cardImages,
Buttons = cardButtons
};