有一个简单的程序,它有一串 "是 "与 "否 "的按钮,当点击-1(是)或+1(否)时,我如何做一个简单的单元测试来检查这些按钮的点击是否在递增或递减。
有没有办法根据答案的最终值来测试是否出现了正确的吐司呢?
int answer = 0;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void yesButton(View view) {
answer= answer -1;
}
public void noButton(View view) {
answer= answer+1;
}
public void diagnosis(View view) {
if (answer > 2) {
Toast.makeText(this, "", Toast.LENGTH_LONG).show();
} else {
Toast.makeText(this, "!", Toast.LENGTH_LONG).show();
}
}
}
你不能为涉及Activity、Toast、Fragment、View或任何子类型的View(如按钮、textView等)的函数创建单元测试。你必须为这些函数创建一个androidTest。
请看您的代码测试示例。
@RunWith(AndroidJUnit4ClassRunner::class)
class IncrementDecrementTest {
@Test
void incrementDecrementTest() {
Espresso.onView(withId(R.id.increment)).perform(click());
Espresso.onView(withId(R.id.button)).perform(click());
Espresso.onView(withText("!")).
inRoot(ToastMatcher()).check(matches(isDisplayed()));
Espresso.onView(withId(R.id.increment)).perform(click());
Espresso.onView(withId(R.id.button)).perform(click());
Espresso.onView(withText("")).
inRoot(ToastMatcher()).check(matches(isDisplayed()));
Espresso.onView(withId(R.id.decrement)).perform(click());
Espresso.onView(withId(R.id.button)).perform(click());
Espresso.onView(withText("!")).
inRoot(ToastMatcher()).check(matches(isDisplayed()));
}
上面的测试需要Espresso库,用来自动执行点击,滚动等操作,还需要一个自定义的匹配器来测试Toast是否被显示。
class ToastMatcher extends TypeSafeMatcher<Root>() {
@Override
void describeTo(Description description) {
description.appendText("is toast");
}
@Override
public Boolean matchesSafely(Root root) {
int type = root.windowLayoutParams.get().getType() ;
if (type == WindowManager.LayoutParams.TYPE_TOAST) {
IBinder windowToken = root.decorView.windowToken;
IBinder val appToken: IBinder = root.decorView.applicationWindowToken;
if (windowToken === appToken) {
return true;
}
}
return false;
}
}