فرض کنیم شما یک Activity Layout دارید که صفحه Welcome را به شما نشان میدهد:
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent"> <Button android:id="@+id/login" android:text="Login" android:layout_width="wrap_content" android:layout_height="wrap_content"/> </LinearLayout>
ما قصد داریم تستی بنویسیم که نشان میدهد هنگامی که یک کاربر بر روی یک دکمه کلیک میکند، برنامه LoginActivity راهاندازی میشود.
public class WelcomeActivity extends Activity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.welcome_activity); final View button = findViewById(R.id.login); button.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { startActivity(new Intent(WelcomeActivity.this, LoginActivity.class)); } }); } }
برای تست کردن چنین چیزی، میتوانیم چک کنیم زمانی که یک کاربر بر روی دکمه “Login” کلیک میکند، کار درستی را آغاز کنیم. از آنجا که Robolectric یک Unit Test Framework است، بنابراین LoginActivity واقعا شروع نمیشود، اما میتوانیم بررسی کنیم که WelcomeActivity کار درستی را آغاز کرده است:
@RunWith(RobolectricTestRunner.class) public class WelcomeActivityTest { @Test public void clickingLogin_shouldStartLoginActivity() { WelcomeActivity activity = Robolectric.setupActivity(WelcomeActivity.class); activity.findViewById(R.id.login).performClick(); Intent expectedIntent = new Intent(activity, LoginActivity.class); Intent actual = shadowOf(RuntimeEnvironment.application).getNextStartedActivity(); assertEquals(expectedIntent.getComponent(), actual.getComponent()); } }
APIهای تستی
Robolectric با کمک مجموعه بزرگی از APIهای تستی، Android Framework را بسط داده است که پیکربندیپذیری و دسترسی به وضعیت داخلی و تاریخچه کامپوننتهای اندرویدی که برای تست مفید هستند را ارائه میدهد.
بسیاری از APIهای تستی، Extensionهایی برای کلاسهای جداگانه اندروید هستند که میتوانند از طریق متد ‘()shadowOf’ مورد بهرهبرداری قرار گیرند:
// retrieves all the toasts that have been displayed... List<Toast> toasts = shadowOf(application).getShownToasts();
APIهای تستی اضافی به عنوان Static Methodها در کلاسهای ویژه به نام shadow قابل دسترسی هستند،که به کلاسهای Android Framework مربوط میشوند:
// simulates a new display being plugged into the device... ShadowDisplay.addDisplay("xlarge-port");
شما میتوانید اسناد APIهای تستی Robolectric را بوسیله نصب Robolectric plugin for Chrome و بازدید از Android API Reference بیابید.
تمام قسمتهای آموزش Robolectric، به صورت دستهبندی شده از اینجا نیز در دسترس است.