ทดสอบบริการ

หากคุณจะใช้ Service ในเครื่องเป็นคอมโพเนนต์ของแอป คุณจะทำสิ่งต่อไปนี้ได้ สร้างการทดสอบแบบมีเครื่องวัดเพื่อยืนยันว่าลักษณะการทำงานถูกต้องได้

AndroidX Test มี API สำหรับการทดสอบออบเจ็กต์ Service ใน การแยก คลาส ServiceTestRule คือกฎ JUnit 4 ที่เริ่มต้น บริการก่อนที่จะเรียกใช้เมธอดการทดสอบหน่วยของคุณ และปิดบริการหลังจาก การทดสอบเสร็จสมบูรณ์ ดูข้อมูลเพิ่มเติมเกี่ยวกับกฎ JUnit 4 ได้ที่ JUnit เอกสารประกอบ

ตั้งค่าสภาพแวดล้อมการทดสอบ

ก่อนที่จะสร้างการทดสอบการผสานรวมสำหรับบริการ โปรดตรวจสอบว่าได้กำหนดค่า โปรเจ็กต์สําหรับการทดสอบแบบมีเครื่องควบคุม ตามที่อธิบายไว้ในตั้งค่าโปรเจ็กต์สําหรับ การทดสอบ AndroidX

สร้างการทดสอบการผสานรวมสำหรับบริการ

คุณควรเขียนแบบทดสอบการผสานรวมเป็นคลาสการทดสอบ JUnit 4 เพื่อดูข้อมูลเพิ่มเติม เกี่ยวกับการสร้างคลาสทดสอบ JUnit 4 และวิธียืนยันความถูกต้องของ JUnit 4 โปรดดู สร้างชั้นเรียนการสอบแบบมีเครื่องวัด

สร้างอินสแตนซ์ ServiceTestRule ในการทดสอบโดยใช้ @Rule หมายเหตุ

KotlinJava

@get:Rule
val serviceRule = ServiceTestRule()


@Rule
public final ServiceTestRule serviceRule = new ServiceTestRule();

ตัวอย่างต่อไปนี้แสดงวิธีที่คุณอาจนำการทดสอบการผสานรวมไปใช้ service. วิธีทดสอบ testWithBoundService() จะยืนยันว่าแอปเชื่อมโยง ไปยังบริการภายในเครื่องได้สำเร็จ และอินเทอร์เฟซบริการทำงานได้ตามปกติ อย่างถูกต้อง

KotlinJava

@Test
@Throws(TimeoutException::class)
fun testWithBoundService() {
 
// Create the service Intent.
 
val serviceIntent = Intent(
     
ApplicationProvider.getApplicationContext<Context>(),
     
LocalService::class.java
 
).apply {
   
// Data can be passed to the service via the Intent.
    putExtra
(SEED_KEY, 42L)
 
}

 
// Bind the service and grab a reference to the binder.
 
val binder: IBinder = serviceRule.bindService(serviceIntent)

 
// Get the reference to the service, or you can call
 
// public methods on the binder directly.
 
val service: LocalService = (binder as LocalService.LocalBinder).getService()

 
// Verify that the service is working correctly.
  assertThat
(service.getRandomInt(), `is`(any(Int::class.java)))
}


@Test
public void testWithBoundService() throws TimeoutException {
 
// Create the service Intent.
 
Intent serviceIntent =
     
new Intent(ApplicationProvider.getApplicationContext(),
       
LocalService.class);

 
// Data can be passed to the service via the Intent.
  serviceIntent
.putExtra(LocalService.SEED_KEY, 42L);

 
// Bind the service and grab a reference to the binder.
 
IBinder binder = serviceRule.bindService(serviceIntent);

 
// Get the reference to the service, or you can call
 
// public methods on the binder directly.
 
LocalService service =
     
((LocalService.LocalBinder) binder).getService();

 
// Verify that the service is working correctly.
  assertThat
(service.getRandomInt()).isAssignableTo(Integer.class);
}

แหล่งข้อมูลเพิ่มเติม

หากต้องการดูข้อมูลเพิ่มเติมเกี่ยวกับหัวข้อนี้ ให้ดูแหล่งข้อมูลเพิ่มเติมต่อไปนี้

ตัวอย่าง