Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 14 additions & 0 deletions maps-compose-widgets/build.gradle.kts
Original file line number Diff line number Diff line change
Expand Up @@ -58,6 +58,12 @@ android {
enableAndroidTestCoverage = true
}
}

testOptions {
unitTests {
isIncludeAndroidResources = true
}
}
}

kotlin {
Expand Down Expand Up @@ -106,6 +112,14 @@ dependencies {
api(libs.maps.utils)

testImplementation(libs.test.junit)
testImplementation(libs.robolectric)
testImplementation(libs.truth)
testImplementation(libs.mockk)
testImplementation(libs.androidx.test.compose.ui)
testImplementation(libs.androidx.test.compose.ui.manifest)
testImplementation(libs.androidx.activity.compose)
testImplementation(libs.maps.testing.robolectric)

androidTestImplementation(platform(libs.androidx.compose.bom))
androidTestImplementation(libs.androidx.test.espresso)
androidTestImplementation(libs.androidx.test.junit.ktx)
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,161 @@
/*
* Copyright 2026 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

package com.google.maps.android.compose.widgets

import android.graphics.Point
import androidx.activity.ComponentActivity
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.runtime.snapshots.Snapshot
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.test.assertIsDisplayed
import androidx.compose.ui.test.junit4.AndroidComposeTestRule
import androidx.compose.ui.test.junit4.v2.createAndroidComposeRule
import androidx.compose.ui.test.onNodeWithText
import androidx.compose.ui.unit.Density
import androidx.compose.ui.unit.dp
import androidx.test.ext.junit.rules.ActivityScenarioRule
import com.google.android.gms.maps.CameraUpdateFactory
import com.google.android.gms.maps.Projection
import com.google.android.gms.maps.model.CameraPosition
import com.google.android.gms.maps.model.LatLng
import com.google.common.truth.Truth.assertThat
import com.google.maps.android.compose.CameraPositionState
import com.google.maps.android.robolectric.annotation.EnableMapsShadows
import com.google.maps.android.robolectric.ktx.createTestMap
import io.mockk.every
import io.mockk.mockk
import org.junit.Rule
import org.junit.Test
import org.junit.runner.RunWith
import org.robolectric.RobolectricTestRunner
import org.robolectric.annotation.Config

// [START maps_compose_widgets_scale_bar_test]
@RunWith(RobolectricTestRunner::class)
@Config(sdk = [34])
@EnableMapsShadows
internal class ScaleBarTest {

@get:Rule
internal val composeTestRule: AndroidComposeTestRule<ActivityScenarioRule<ComponentActivity>, ComponentActivity> =
createAndroidComposeRule<ComponentActivity>()

@Test
internal fun testCalculateDistance_computesExpectedCanvasDistance() {
val projection = mockk<Projection>()
every { projection.fromScreenLocation(Point(0, 0)) } returns LatLng(0.0, 0.0)
every { projection.fromScreenLocation(Point(100, 0)) } returns LatLng(0.0, 0.001)

val result = calculateDistance(
projection = projection,
width = 100.dp,
density = Density(1f, 1f),
)

// 0.001 deg of longitude at the equator is ~111.19 m; the drawn scale bar spans 8/9 of the canvas (~98 m).
assertThat(result).isEqualTo(98)
}

@Test
internal fun testCalculateDistance_atTarget_computesExpectedCenterSpanDistance() {
val equator = LatLng(0.0, 0.0)
val highLatitude = LatLng(60.0, 0.0)
val density = Density(1f, 1f)
val width = 100.dp

val equatorMap = createTestMap().apply {
moveCamera(CameraUpdateFactory.newLatLngZoom(equator, 12f))
}
val equatorDistance = calculateDistance(equatorMap.projection, width, density, target = equator)

// At zoom 12 on the equator, 100 px spans ~3,822 m; 8/9 of that is ~3,397 m.
assertThat(equatorDistance).isIn(3350..3450)

val highLatMap = createTestMap().apply {
moveCamera(CameraUpdateFactory.newLatLngZoom(highLatitude, 12f))
}
val highLatDistance = calculateDistance(highLatMap.projection, width, density, target = highLatitude)

// At 60 deg latitude, cos(60 deg) = 0.5, so the same pixel width spans half the ground distance (~1,699 m).
assertThat(highLatDistance).isIn(1650..1750)
}

@Test
internal fun testScaleBar_rendersWithoutCrashing() {
val cameraState = CameraPositionState(
position = CameraPosition.fromLatLngZoom(LatLng(37.7749, -122.4194), 12f),
)

composeTestRule.setContent {
ScaleBar(
cameraPositionState = cameraState,
width = 80.dp,
height = 50.dp,
textColor = Color.Black,
lineColor = Color.Blue,
shadowColor = Color.White,
)
}

composeTestRule.waitForIdle()
// cameraState is not bound to a GoogleMap, so projection is null and ScaleBar renders the 0 fallback labels.
composeTestRule.onNodeWithText("0 ft").assertIsDisplayed()

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Just to understand it: the state is never attached to a map, so the projection is null and we render always the 0 fallback, right? Would it make sense to add a comment here, so nobody thinks we are checking a real label?

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yes, exactly — cameraState isn't attached to a GoogleMap in that test, so projection is null and ScaleBar renders the 0 fallback labels. Added an explicit comment in 50602e48 to make that clear (and I'm adding live GoogleMap-bound ScaleBar and adversarial edge-case tests in a follow-up PR).

composeTestRule.onNodeWithText("0 m").assertIsDisplayed()
}

@Test
internal fun testDisappearingScaleBar_showsOnCameraChangeAndHidesAfterDuration() {
composeTestRule.mainClock.autoAdvance = false
val cameraState = CameraPositionState(
position = CameraPosition.fromLatLngZoom(LatLng(37.7749, -122.4194), 10f),
)

composeTestRule.setContent {
Box(modifier = Modifier.fillMaxSize()) {
DisappearingScaleBar(
cameraPositionState = cameraState,
visibilityDurationMillis = 1_000,
)
}
}

composeTestRule.mainClock.advanceTimeByFrame()
composeTestRule.onNodeWithText("0 m").assertIsDisplayed()

// Advance past visibilityDurationMillis (1,000 ms) and the exit fade animation.
composeTestRule.mainClock.advanceTimeBy(2_000L)
composeTestRule.mainClock.advanceTimeByFrame()
composeTestRule.onNodeWithText("0 m").assertDoesNotExist()

// Updating camera position re-triggers the LaunchedEffect and shows the scale bar again.
Snapshot.withMutableSnapshot {
cameraState.position = CameraPosition.fromLatLngZoom(LatLng(37.7749, -122.4194), 14f)
}
composeTestRule.mainClock.advanceTimeByFrame()
composeTestRule.mainClock.advanceTimeBy(200L)
composeTestRule.mainClock.advanceTimeByFrame()
composeTestRule.onNodeWithText("0 m").assertIsDisplayed()

// Advance past visibilityDurationMillis again and confirm the scale bar hides.
composeTestRule.mainClock.advanceTimeBy(2_000L)
composeTestRule.mainClock.advanceTimeByFrame()
composeTestRule.onNodeWithText("0 m").assertDoesNotExist()
}
}
// [END maps_compose_widgets_scale_bar_test]
Original file line number Diff line number Diff line change
Expand Up @@ -39,15 +39,17 @@ import com.google.android.gms.maps.model.CameraPosition
import com.google.android.gms.maps.model.LatLng
import com.google.common.truth.Truth.assertThat
import com.google.maps.android.robolectric.annotation.EnableMapsShadows
import com.google.maps.android.robolectric.shadows.ShadowGoogleMap
import com.google.maps.android.robolectric.shadows.ShadowMapView
import com.google.maps.android.robolectric.ktx.circles
import com.google.maps.android.robolectric.ktx.clickMarker
import com.google.maps.android.robolectric.ktx.createTestMap
import com.google.maps.android.robolectric.ktx.markers
import com.google.maps.android.robolectric.truth.GoogleMapSubject.Companion.assertThat
import com.google.maps.android.robolectric.truth.LatLngSubject
import org.junit.Rule
import org.junit.Test
import org.junit.runner.RunWith
import org.robolectric.RobolectricTestRunner
import org.robolectric.annotation.Config
import org.robolectric.shadow.api.Shadow

// [START maps_compose_google_map_composable_test]
@RunWith(RobolectricTestRunner::class)
Expand Down Expand Up @@ -91,8 +93,7 @@ internal class GoogleMapTest {

composeTestRule.waitForIdle()

assertThat(underlyingMap).isNotNull()
val shadowMap = Shadow.extract(underlyingMap) as ShadowGoogleMap
val map = checkNotNull(underlyingMap)

// Verify camera position
LatLngSubject.assertThat(cameraState.position.target)
Expand All @@ -101,16 +102,16 @@ internal class GoogleMapTest {
assertThat(cameraState.position.zoom).isEqualTo(11f)

// Verify Marker rendered via MapApplier
assertThat(shadowMap.markers).hasSize(1)
val marker = shadowMap.markers.first()
assertThat(marker.title).isEqualTo("Sydney Flagship")
assertThat(map).hasMarkerCount(1)
assertThat(map).hasMarkerWithTitle("Sydney Flagship")
val marker = map.markers.first()
LatLngSubject.assertThat(marker.position)
.isWithin(1.0)
.of(sydney)

// Verify Circle rendered via MapApplier
assertThat(shadowMap.circles).hasSize(1)
val circle = shadowMap.circles.first()
assertThat(map).hasCircleCount(1)
val circle = map.circles.first()
assertThat(circle.radius).isEqualTo(1500.0)
LatLngSubject.assertThat(circle.center)
.isWithin(1.0)
Expand Down Expand Up @@ -146,12 +147,11 @@ internal class GoogleMapTest {

composeTestRule.waitForIdle()

assertThat(underlyingMap).isNotNull()
val shadowMap = Shadow.extract(underlyingMap) as ShadowGoogleMap
val marker = shadowMap.markers.first()
val map = checkNotNull(underlyingMap)
val marker = map.markers.first()

// Simulate user clicking on marker
shadowMap.clickMarker(marker)
map.clickMarker(marker)
composeTestRule.waitForIdle()

assertThat(markerClicked).isTrue()
Expand Down Expand Up @@ -183,16 +183,15 @@ internal class GoogleMapTest {
}

composeTestRule.waitForIdle()
assertThat(underlyingMap).isNotNull()
val shadowMap = Shadow.extract(underlyingMap) as ShadowGoogleMap
assertThat(shadowMap.markers).hasSize(1)
val map = checkNotNull(underlyingMap)
assertThat(map).hasMarkerCount(1)

// Mutate Compose state to remove marker
showMarker = false
composeTestRule.waitForIdle()

// Assert that the marker was dynamically removed from the map
assertThat(shadowMap.markers).isEmpty()
assertThat(map).hasNoMarkers()
}

@Test
Expand Down Expand Up @@ -250,7 +249,7 @@ internal class GoogleMapTest {
internal fun testGoogleMap_customMapViewDelegateFactory_lifecycleAndMarkerComposable() {
val expectedPosition = CameraPosition.fromLatLngZoom(sydney, 13f)
val lifecycleEvents = mutableListOf<String>()
val fakeGoogleMap = ShadowMapView.createFakeGoogleMap()
val fakeGoogleMap = createTestMap()
var capturedOptions: GoogleMapOptions? = null
var customDelegate: MapViewDelegate<FrameLayout>? = null

Expand Down Expand Up @@ -314,9 +313,8 @@ internal class GoogleMapTest {
assertThat(capturedOptions?.camera).isEqualTo(expectedPosition)
assertThat(lifecycleEvents).containsExactly("onCreate", "onStart", "onResume").inOrder()

val shadowMap = Shadow.extract(fakeGoogleMap) as ShadowGoogleMap
assertThat(shadowMap.markers).hasSize(2)
assertThat(shadowMap.markers.map { it.title }).containsExactly("Delegated Marker", "Composable Marker")
assertThat(fakeGoogleMap).hasMarkerCount(2)
assertThat(fakeGoogleMap.markers.map { it.title }).containsExactly("Delegated Marker", "Composable Marker")
}
}
// [END maps_compose_google_map_composable_test]
Loading