ArCoreTestRule


class ArCoreTestRule : ExternalResource


A JUnit TestRule that provides a way to simulate ARCore for Jetpack XR's perception of the real world, enabling you to write reliable and clean tests for ARCore for Jetpack XR applications without needing a physical device or emulator. You can control various aspects of the XR environment, such as the presence of planes, augmented objects, images, QR codes, the user's face or hands, etc.

Writing effective ARCore for Jetpack XR tests involves the kotlinx-coroutines-test library, namely TestScopes and TestDispatchers. Unit tests should typically execute within a runTest block and pass a StandardTestDispatcher to the appropriate androidx.xr.runtime.Session.

Any changes to the simulated environment require coroutines to be executed to enable ARCore for Jetpack XR to consume the new information. To achieve this, follow any set of changes to your ArCoreTestRule trackables and tester objects with a call to advanceUntilIdle(). This will execute the TestDispatcher's queued coroutines until they complete or suspend, at which point the ARCore for Jetpack XR runtime will have consumed the data based on the state of the ArCoreTestRule. Further, any new coroutine that the test launches, whose results later test steps depend on (e.g. Plane.subscribe), should also be followed by advanceUntilIdle(). This will delay the test until the coroutine has completed or yields.

Tests using ArCoreTestRule typically follow these phases:

  1. Environment Setup: Configure the XR environment by setting properties on the ArCoreTestRule. Follow any set of changes to the ArCoreTestRule values with a call to advanceUntilIdle().

  2. Action/Collection: Perform actions that would trigger changes to ARCore for Jetpack XR's perception system, such as launching coroutines (e.g., subscribing to Trackable objects) or modifying the androidx.xr.runtime.Session configuration. For these actions, follow immediately with a call to advanceUntilIdle() to ensure the changes are processed. If the action is simply to read the state of static objects (like a hand or the device pose), advanceUntilIdle() is not required.

  3. Assertion: Check the state of ARCore for Jetpack XR objects (e.g., Plane, AugmentedImage, ArDevice) to verify that the data was consumed and read correctly.

import androidx.activity.ComponentActivity
import androidx.test.ext.junit.runners.AndroidJUnit4
import androidx.xr.arcore.ArDevice
import androidx.xr.arcore.Plane
import androidx.xr.arcore.PlaneLabel
import androidx.xr.arcore.PlaneType
import androidx.xr.arcore.testing.ArCoreTestRule
import androidx.xr.arcore.testing.TestPlane
import androidx.xr.runtime.Config
import androidx.xr.runtime.DeviceTrackingMode
import androidx.xr.runtime.PlaneTrackingMode
import androidx.xr.runtime.Session
import androidx.xr.runtime.SessionCreateSuccess
import androidx.xr.runtime.manifest.SCENE_UNDERSTANDING_COARSE
import androidx.xr.runtime.math.Pose
import androidx.xr.runtime.math.Quaternion
import androidx.xr.runtime.math.Vector3

@RunWith(AndroidJUnit4::class)
class ArCoreTestSamples {
    // Declare an instance of ArCoreTestRule with @Rule
    @Rule @JvmField val arCoreTestRule = ArCoreTestRule()

    private lateinit var activityController: ActivityController<ComponentActivity>
    private lateinit var activity: ComponentActivity
    private lateinit var testDispatcher: TestDispatcher
    private lateinit var testScope: TestScope
    private lateinit var session: Session

    // Configure the TestScope, Dispatcher, and running Session before each test
    @Before
    fun setUp(): Unit = runBlocking {
        testDispatcher = StandardTestDispatcher()
        testScope = TestScope(testDispatcher)
        activityController = Robolectric.buildActivity(ComponentActivity::class.java)
        activity = activityController.get()

        // Grant the application required permissions
        shadowOf(activity.application).grantPermissions(SCENE_UNDERSTANDING_COARSE)

        // Start the Activity and ensure it's running
        activityController.create().start().resume()

        session =
            (Session.create(context = activity, coroutineContext = testDispatcher)
                    as SessionCreateSuccess)
                .session
        session.configure(
            Config.Builder()
                .setPlaneTracking(PlaneTrackingMode.HORIZONTAL_AND_VERTICAL)
                .setDeviceTracking(DeviceTrackingMode.SPATIAL)
                .build()
        )
    }

    @Test
    fun plane_subscribe_detectsPlane() =
        runTest(testDispatcher) {
            val plane1 = TestPlane(PlaneType.HORIZONTAL_UPWARD_FACING, PlaneLabel.FLOOR)
            arCoreTestRule.addTrackables(plane1)
            advanceUntilIdle()

            var foundPlanes = emptyList<Plane>()
            testScope.launch {
                Plane.subscribe(session).collect { foundPlanes = it.toList() }
            }
            advanceUntilIdle()

            assertThat(foundPlanes.single().type).isEqualTo(PlaneType.HORIZONTAL_UPWARD_FACING)
        }

    @Test
    fun arDevice_getInstance_pose_updates() =
        runTest(testDispatcher) {
            val expectedPose = Pose(Vector3(1f, 2f, 3f), Quaternion(4f, 5f, 6f, 7f))
            arCoreTestRule.deviceTester.pose = expectedPose
            advanceUntilIdle()

            val underTest = ArDevice.getInstance(session)

            assertThat(underTest.state.value.devicePose).isEqualTo(expectedPose)

            arCoreTestRule.deviceTester.pose = Pose.Identity
            advanceUntilIdle()

            assertThat(underTest.state.value.devicePose).isEqualTo(Pose.Identity)
        }
}

Summary

Public constructors

Public functions

Unit
addTrackables(vararg trackables: TestTrackable)

Adds the given TestTrackable objects and registers them with this ArCoreTestRule.

Unit

Clears the map of UUID instances to Pose instances.

List<TestSpatialAnnotation>

A list of all TestSpatialAnnotation objects in the environment.

UUID

Supply the Pose of an androidx.xr.arcore.Anchor to be persisted outside the androidx.xr.runtime.Session.

Protected functions

open Unit
open Unit

Public properties

Int

The maximum number of androidx.xr.arcore.Anchor objects that can be loaded at once in the runtime.

List<TestAugmentedImage>

A list of all TestAugmentedImage objects in the environment.

List<TestAugmentedObject>

A list of all TestAugmentedObject objects in the environment.

ArDeviceTester

The object representing the user's device in the environment.

FaceTester

The object representing the user's face.

GeospatialTester

A test representation of the device's androidx.xr.arcore.Geospatial status.

DepthTester

A test representation of the device's left androidx.xr.arcore.Depth data.

EyeTester

The object representing the user's left eye in the environment.

HandTester

The object representing the user's left hand in the environment.

RenderViewpointTester

A test representation of the device's left androidx.xr.arcore.RenderViewpoint.

DepthTester

A test representation of the device's mono androidx.xr.arcore.Depth data.

RenderViewpointTester

A test representation of the device's mono androidx.xr.arcore.RenderViewpoint.

Map<UUID, Pose>

A Map of UUID to Anchor Poses stored outside the session.

List<TestPlane>

A list of all TestPlane objects in the environment.

List<TestQrCode>

A list of all TestQrCode objects in the environment.

DepthTester

A test representation of the device's right androidx.xr.arcore.Depth data.

EyeTester

The object representing the user's right eye in the environment.

HandTester

The object representing the user's right hand in the environment.

RenderViewpointTester

A test representation of the device's right androidx.xr.arcore.RenderViewpoint.

Inherited functions

From org.junit.rules.ExternalResource
Statement
apply(base: Statement, description: Description)

Public constructors

ArCoreTestRule

Added in 1.0.0
ArCoreTestRule()

Public functions

addTrackables

Added in 1.0.0
fun addTrackables(vararg trackables: TestTrackable): Unit

Adds the given TestTrackable objects and registers them with this ArCoreTestRule.

Objects that are added are not removed during the lifetime of the test. Instead, their androidx.xr.arcore.TrackingState will be updated based on their TestTrackable.isVisible property and the androidx.xr.runtime.Session configuration.

Parameters
vararg trackables: TestTrackable

TestTrackable objects to add

clearPersistedAnchors

Added in 1.0.0
fun clearPersistedAnchors(): Unit

Clears the map of UUID instances to Pose instances.

getSpatialAnnotations

Added in 1.1.0-alpha02
@ExperimentalSpatialAnnotationsApi
fun getSpatialAnnotations(): List<TestSpatialAnnotation>

A list of all TestSpatialAnnotation objects in the environment. Tracking must be configured via androidx.xr.runtime.Session.configure in order for an added object to be ingested by the runtime.

persistAnchor

Added in 1.0.0
fun persistAnchor(pose: Pose): UUID

Supply the Pose of an androidx.xr.arcore.Anchor to be persisted outside the androidx.xr.runtime.Session. Persisted Anchors can be loaded by their UUID.

Parameters
pose: Pose

the Pose at which the test will persist an Anchor

Returns
UUID

the UUID of the newly persisted Anchor

Protected functions

after

protected open fun after(): Unit

before

Added in 1.0.0
protected open fun before(): Unit

Public properties

anchorResourceLimit

Added in 1.0.0
var anchorResourceLimit: Int

The maximum number of androidx.xr.arcore.Anchor objects that can be loaded at once in the runtime. Defaults to 6.

augmentedImages

Added in 1.0.0
val augmentedImages: List<TestAugmentedImage>

A list of all TestAugmentedImage objects in the environment. Tracking must be configured via androidx.xr.runtime.Session.configure in order for an added object to be ingested by the runtime.

augmentedObjects

Added in 1.0.0
val augmentedObjects: List<TestAugmentedObject>

A list of all TestAugmentedObject objects in the environment. Tracking must be configured via androidx.xr.runtime.Session.configure in order for an added object to be ingested by the runtime.

deviceTester

Added in 1.0.0
val deviceTester: ArDeviceTester

The object representing the user's device in the environment. androidx.xr.runtime.DeviceTrackingMode.LAST_KNOWN must be configured for it to be ingested by the runtime.

faceTester

Added in 1.0.0
val faceTester: FaceTester

The object representing the user's face. Config.faceTracking must be set to androidx.xr.runtime.FaceTrackingMode.BLEND_SHAPES for it to be integrated by the runtime. FaceTester.isValid must be set to true for the face's blend shape and confidence values to update in the API.

geospatialTester

Added in 1.0.0
val geospatialTester: GeospatialTester

A test representation of the device's androidx.xr.arcore.Geospatial status.

leftDepthTester

Added in 1.0.0
val leftDepthTester: DepthTester

A test representation of the device's left androidx.xr.arcore.Depth data.

leftEyeTester

Added in 1.0.0
val leftEyeTester: EyeTester

The object representing the user's left eye in the environment. androidx.xr.runtime.EyeTrackingMode.COARSE_TRACKING or androidx.xr.runtime.EyeTrackingMode.FINE_TRACKING must be configured for it to be ingested by the runtime. EyeTester.isOpen must be set to true for the eye's pose to update in the API.

leftHandTester

Added in 1.0.0
val leftHandTester: HandTester

The object representing the user's left hand in the environment. androidx.xr.runtime.HandTrackingMode.BOTH must be configured for it to be ingested by the runtime. HandTester.isVisible must be set to true for the hand's pose to update in the API.

leftRenderViewpointTester

Added in 1.0.0
val leftRenderViewpointTester: RenderViewpointTester

A test representation of the device's left androidx.xr.arcore.RenderViewpoint.

monoDepthTester

Added in 1.0.0
val monoDepthTester: DepthTester

A test representation of the device's mono androidx.xr.arcore.Depth data.

monoRenderViewpointTester

Added in 1.0.0
val monoRenderViewpointTester: RenderViewpointTester

A test representation of the device's mono androidx.xr.arcore.RenderViewpoint.

persistedAnchorPoses

Added in 1.0.0
val persistedAnchorPoses: Map<UUID, Pose>

A Map of UUID to Anchor Poses stored outside the session.

planes

Added in 1.0.0
val planes: List<TestPlane>

A list of all TestPlane objects in the environment. Tracking must be configured via androidx.xr.runtime.Session.configure in order for an added plane to be ingested by the runtime.

qrCodes

Added in 1.0.0
val qrCodes: List<TestQrCode>

A list of all TestQrCode objects in the environment. Tracking must be configured via androidx.xr.runtime.Session.configure in order for an added object to be ingested by the runtime.

rightDepthTester

Added in 1.0.0
val rightDepthTester: DepthTester

A test representation of the device's right androidx.xr.arcore.Depth data.

rightEyeTester

Added in 1.0.0
val rightEyeTester: EyeTester

The object representing the user's right eye in the environment. androidx.xr.runtime.EyeTrackingMode.COARSE_TRACKING or androidx.xr.runtime.EyeTrackingMode.FINE_TRACKING must be configured for it to be ingested by the runtime. EyeTester.isOpen must be set to true for the eye's pose to update in the API.

rightHandTester

Added in 1.0.0
val rightHandTester: HandTester

The object representing the user's right hand in the environment. androidx.xr.runtime.HandTrackingMode.BOTH must be configured for it to be ingested by the runtime. HandTester.isVisible must be set to true for the hand's pose to update in the API.

rightRenderViewpointTester

Added in 1.0.0
val rightRenderViewpointTester: RenderViewpointTester

A test representation of the device's right androidx.xr.arcore.RenderViewpoint.