### Install App and Test App (Flavor2 Debug)
Source: https://github.com/googlesamples/android-testing-templates/blob/master/AndroidTestingBlueprint/README.md
Install the application and its corresponding test application for Flavor2 Debug using Gradle.
```sh
./gradlew app:installFlavor2Debug app:installFlavor2DebugAndroidTest
```
--------------------------------
### Example Usage of Flavor1Class (Java)
Source: https://github.com/googlesamples/android-testing-templates/blob/master/_autodocs/api-reference/flavor-classes.md
Demonstrates how to instantiate and check the readiness of Flavor1Class. Catches ClassNotFoundException if the flavor1 variant is not being built.
```java
try {
Flavor1Class flavor1 = new Flavor1Class();
if (flavor1.isReady()) {
System.out.println("Flavor1 features available");
}
} catch (ClassNotFoundException e) {
System.out.println("Not building flavor1 variant");
}
```
--------------------------------
### Example Usage of Flavor1Class (Kotlin)
Source: https://github.com/googlesamples/android-testing-templates/blob/master/_autodocs/api-reference/flavor-classes.md
Demonstrates how to instantiate and check the readiness of Flavor1Class. Catches ClassNotFoundException if the flavor1 variant is not being built.
```kotlin
try {
val flavor1 = Flavor1Class()
if (flavor1.isReady()) {
println("Flavor1 features available")
}
} catch (e: ClassNotFoundException) {
println("Not building flavor1 variant")
}
```
--------------------------------
### Dependency Injection Example
Source: https://github.com/googlesamples/android-testing-templates/blob/master/_autodocs/MODULE_ARCHITECTURE.md
Shows a basic example of using a dependency injection container to provide instances of module classes. This pattern is recommended for more complex scenarios to manage dependencies.
```kotlin
// Container provides instances
val container = DIContainer()
val plainKotlin = container.providePlainKotlin()
val library = container.provideAndroidLibrary()
```
--------------------------------
### Example Usage of MyPlainKotlinClass.isReady()
Source: https://github.com/googlesamples/android-testing-templates/blob/master/_autodocs/api-reference/plain-module-kotlin.md
Demonstrates how to instantiate MyPlainKotlinClass and check its readiness state. Also shows its usage within an Android activity context.
```kotlin
// Create instance
val instance = MyPlainKotlinClass()
// Check readiness
if (instance.isReady()) {
// Proceed with operations
println("Module is ready")
}
// In activity context (from HelloTestingBlueprintActivity)
plainKotlinClassInstance = MyPlainKotlinClass()
val isReady = plainKotlinClassInstance.isReady()
```
--------------------------------
### Install App and Test Module for ADB
Source: https://github.com/googlesamples/android-testing-templates/blob/master/AndroidTestingBlueprint/README.md
Install the main application and a specific flavor of the test-only module before running tests via ADB.
```gradle
./gradlew app:installFlavor1Debug module-flavor1-androidTest-only:installDebug
```
--------------------------------
### Mockito Mock Setup Patterns
Source: https://github.com/googlesamples/android-testing-templates/blob/master/_autodocs/TESTING_FRAMEWORKS.md
Illustrates various ways to set up mock behavior, including simple return values, chaining, exception throwing, and answer callbacks.
```kotlin
// Simple return value
mockWhen(object.method()).thenReturn(value)
// Chain setup
mockWhen(object.method1()).thenReturn(obj)
.thenReturn(obj2)
// Exception throwing
mockWhen(object.method()).thenThrow(Exception())
// Answer callbacks
mockWhen(object.method()).thenAnswer { invocation ->
// Custom logic
}
```
--------------------------------
### Dependency Version Management Example
Source: https://github.com/googlesamples/android-testing-templates/blob/master/_autodocs/BUILD_SYSTEM.md
Demonstrates how to define dependency versions in the root build.gradle file and access them in module build files using ext properties.
```gradle
// Root build.gradle defines version
ext {
supportLibVersion = "27.0.1"
}
// Module build.gradle uses property
implementation "com.android.support:appcompat-v7:$supportLibVersion"
```
--------------------------------
### Dependency Tree Example
Source: https://github.com/googlesamples/android-testing-templates/blob/master/_autodocs/MODULE_ARCHITECTURE.md
Visualizes the dependency tree of an application module, showing direct and transitive dependencies. This helps in understanding how modules and their libraries are included.
```plaintext
app
├── module-plain-kotlin
│ └── org.jetbrains.kotlin:kotlin-stdlib-jre7
├── module-android-library
│ └── (no dependencies)
└── com.android.support:appcompat-v7
```
--------------------------------
### MyPlainKotlinClass Local Unit Test Example
Source: https://github.com/googlesamples/android-testing-templates/blob/master/_autodocs/api-reference/plain-module-kotlin.md
An example of a local unit test for MyPlainKotlinClass using JUnit 4, verifying the behavior of the isReady() method.
```kotlin
// Example test structure (based on project patterns)
import org.junit.Test
import org.junit.Assert.assertTrue
class MyPlainKotlinClassTest {
@Test
fun testIsReady() {
val instance = MyPlainKotlinClass()
assertTrue(instance.isReady())
}
}
```
--------------------------------
### Resource Localization Example
Source: https://github.com/googlesamples/android-testing-templates/blob/master/_autodocs/RESOURCE_ORGANIZATION.md
Demonstrates how to structure resource directories for multi-language support. Each `strings.xml` file in a language-specific directory (e.g., `values-fr`) provides translations for the same string IDs defined in the default `values/strings.xml`.
```xml
Android Testing Blueprint
```
```xml
Plan de Test Android
```
--------------------------------
### Transitive Dependency Example
Source: https://github.com/googlesamples/android-testing-templates/blob/master/_autodocs/MODULE_ARCHITECTURE.md
Explains how dependencies of included modules are inherited by the main application. This example shows that when the app includes a module, it also inherits that module's dependencies.
```plaintext
app depends on module-android-library
module-android-library depends on com.android.support:appcompat-v7
Result: app automatically includes appcompat-v7
```
--------------------------------
### App Module Integration Example
Source: https://github.com/googlesamples/android-testing-templates/blob/master/_autodocs/MODULE_ARCHITECTURE.md
Shows how the main application activity instantiates and uses classes from other modules (plain Kotlin and Android library). Ensure dependencies are correctly set up in the build files.
```kotlin
class HelloTestingBlueprintActivity : AppCompatActivity() {
// Dependency from plain module
private lateinit var plainKotlinClassInstance: MyPlainKotlinClass
// Dependency from Android library module
private lateinit var androidLibraryClassInstance: AndroidLibraryModuleClass
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_hello_testing_blueprint)
// Instantiate module classes
plainKotlinClassInstance = MyPlainKotlinClass()
androidLibraryClassInstance = AndroidLibraryModuleClass()
}
fun onClick(view: View) {
// Use module methods
if (plainKotlinClassInstance.isReady() &&
androidLibraryClassInstance.isReady()) {
// Update UI
}
}
}
```
--------------------------------
### List Connected Devices
Source: https://github.com/googlesamples/android-testing-templates/blob/master/_autodocs/QUICK_START.md
Use the adb devices command to list all connected devices and emulators. Ensure the emulator is started if no devices are found.
```bash
# List devices
```
```bash
adb devices
```
--------------------------------
### Example onClick Handler Logic
Source: https://github.com/googlesamples/android-testing-templates/blob/master/_autodocs/api-reference/espresso-testing.md
This Kotlin code snippet shows the logic within an onClick handler that updates a TextView based on module readiness.
```kotlin
fun onClick(view: View) {
if (plainKotlinClassInstance.isReady() &&
androidLibraryClassInstance.isReady()) {
androidTestingRocksTextView.text = getString(R.string.android_testing_rocks)
}
}
```
--------------------------------
### Example Usage of MyPlainJavaClass isReady Method
Source: https://github.com/googlesamples/android-testing-templates/blob/master/_autodocs/api-reference/plain-module-java.md
Demonstrates how to create an instance of MyPlainJavaClass and check its readiness state. This code can be used in various Java environments, including Android activities.
```java
// Create instance
MyPlainJavaClass instance = new MyPlainJavaClass();
// Check readiness
if (instance.isReady()) {
// Proceed with operations
System.out.println("Module is ready");
}
// In activity context (from HelloTestingBlueprintActivity)
mPlainJavaClassInstance = new MyPlainJavaClass();
boolean isReady = mPlainJavaClassInstance.isReady();
```
--------------------------------
### Hamcrest Assertion Examples
Source: https://github.com/googlesamples/android-testing-templates/blob/master/_autodocs/TESTING_FRAMEWORKS.md
Demonstrates various assertion matchers provided by the Hamcrest library for more expressive assertions.
```kotlin
import org.hamcrest.CoreMatchers.*
assertThat(actual, is(expected))
assertThat(actual, notNullValue())
assertThat(actual, nullValue())
assertThat(actual, instanceOf(Class::class.java))
assertThat(items, hasItem(expected))
assertThat(text, containsString(substring))
assertThat(number, greaterThan(threshold))
assertThat(number, lessThan(threshold))
```
--------------------------------
### Example Test Methods for Extension
Source: https://github.com/googlesamples/android-testing-templates/blob/master/_autodocs/api-reference/espresso-testing.md
These are example method signatures for tests that can be added to extend the testing template. They cover editable fields, list interactions, navigation flows, and error states.
```kotlin
@Test
fun testEditableFields() { /* ... */ }
```
```kotlin
@Test
fun testListInteraction() { /* ... */ }
```
```kotlin
@Test
fun testNavigationFlow() { /* ... */ }
```
```kotlin
@Test
fun testErrorStates() { /* ... */ }
```
--------------------------------
### View Binding in Activity (Kotlin/Java)
Source: https://github.com/googlesamples/android-testing-templates/blob/master/_autodocs/RESOURCE_ORGANIZATION.md
Example of how to reference UI elements like TextViews in an Activity using findViewById.
```kotlin
// Kotlin
androidTestingRocksTextView = findViewById(R.id.text_view_rocks)
```
```java
// Java
mAndroidTestingRocksTextView = (TextView) findViewById(R.id.text_view_rocks);
```
--------------------------------
### Common Strings in Android Flavor Example
Source: https://github.com/googlesamples/android-testing-templates/blob/master/_autodocs/api-reference/flavor-classes.md
Defines common string resources used across all flavors. These can be overridden by flavor-specific resources.
```xml
Android Testing BlueprintAndroid Testing Rocks!
```
--------------------------------
### Conditional Compilation Example (Commented)
Source: https://github.com/googlesamples/android-testing-templates/blob/master/_autodocs/api-reference/flavor-classes.md
Shows a commented-out Kotlin code example that would cause a compilation error if a flavor-specific class is not available. This pattern is typically avoided.
```kotlin
// This would cause compilation error if Flavor1Class unavailable
// Typically avoided; instead use reflection or conditional compilation
```
--------------------------------
### Build Project with Gradle Wrapper
Source: https://github.com/googlesamples/android-testing-templates/blob/master/_autodocs/QUICK_START.md
Build the Android Testing Templates project using the Gradle wrapper. This command ensures the project is built correctly without requiring a separate Gradle installation.
```bash
# Using Gradle wrapper (no Gradle installation needed)
./gradlew build
```
--------------------------------
### Kotlin onClick Example Usage
Source: https://github.com/googlesamples/android-testing-templates/blob/master/_autodocs/api-reference/main-activity.md
Illustrates how the onClick method is typically invoked via layout XML binding in Kotlin. The actual logic within onClick checks module readiness before updating UI text.
```kotlin
// Layout XML binding (typically in activity_hello_testing_blueprint.xml)
//
// When button is clicked, onClick is invoked automatically
// If both modules are ready, the text view displays the success message
```
--------------------------------
### Release Build ProGuard Rules
Source: https://github.com/googlesamples/android-testing-templates/blob/master/_autodocs/BUILD_SYSTEM.md
Example ProGuard rules for release builds to obfuscate and minimize code. These rules are project-specific and should be adapted accordingly.
```proguard
# Example rules (project specific)
-keep public class * extends android.app.Activity
-keep public class * extends android.app.Service
```
--------------------------------
### Configure Flavor Dimensions and Product Flavors
Source: https://github.com/googlesamples/android-testing-templates/blob/master/_autodocs/api-reference/flavor-classes.md
Define flavor dimensions and product flavors in your app/build.gradle file. This setup allows for building different app variants with distinct configurations.
```gradle
flavorDimensions "defaultDimension"
productFlavors {
flavor1 {
applicationId 'com.example.android.testing.blueprint.flavor1'
}
flavor2 {
applicationId 'com.example.android.testing.blueprint.flavor2'
}
}
```
--------------------------------
### Run Tests via ADB
Source: https://github.com/googlesamples/android-testing-templates/blob/master/AndroidTestingBlueprint/README.md
Execute instrumentation tests on a device or emulator using the ADB shell command after installation.
```shell
adb shell am instrument -w com.example.android.testing.blueprint.test/android.support.test.runner.AndroidJUnitRunner
```
--------------------------------
### Flavor-Specific Strings in Android Flavor Example
Source: https://github.com/googlesamples/android-testing-templates/blob/master/_autodocs/api-reference/flavor-classes.md
Defines string resources specific to a particular flavor (e.g., flavor1). These override common resources for that flavor.
```xml
Testing Blueprint - Flavor 1
```
--------------------------------
### Package Naming Convention Example
Source: https://github.com/googlesamples/android-testing-templates/blob/master/_autodocs/MODULE_ARCHITECTURE.md
Illustrates the standard package naming convention for classes within an Android project, including main app classes and classes within different module types.
```plaintext
com.example.android.testing.blueprint
├── (main app classes - HelloTestingBlueprintActivity)
├── .plainkotlinmodule.MyPlainKotlinClass
├── .plainjavamodule.MyPlainJavaClass
├── .androidlibrarymodule.AndroidLibraryModuleClass
└── Flavor1Class (flavor1 only)
```
--------------------------------
### MyPlainJavaClass JUnit Test Example
Source: https://github.com/googlesamples/android-testing-templates/blob/master/_autodocs/api-reference/plain-module-java.md
An example of a JUnit test for the MyPlainJavaClass. It demonstrates how to test the isReady method by asserting that it returns true.
```java
// Example test structure (based on project patterns)
import org.junit.Test;
import static org.junit.Assert.assertTrue;
public class MyPlainJavaClassTest {
@Test
public void testIsReady() {
MyPlainJavaClass instance = new MyPlainJavaClass();
assertTrue(instance.isReady());
}
}
```
--------------------------------
### Explore Project Code
Source: https://github.com/googlesamples/android-testing-templates/blob/master/_autodocs/QUICK_START.md
Navigate to the main activity file to understand its structure and dependencies on other modules.
```bash
# Open main activity
# AndroidTestingBlueprint-kotlinApp/app/src/main/.../HelloTestingBlueprintActivity.kt
# Notice how it uses classes from other modules:
# - MyPlainKotlinClass from module-plain-kotlin
# - AndroidLibraryModuleClass from module-android-library
```
--------------------------------
### JUnit Assertion Examples
Source: https://github.com/googlesamples/android-testing-templates/blob/master/_autodocs/TESTING_FRAMEWORKS.md
Provides a collection of common assertion methods available in the JUnit testing framework.
```kotlin
import org.junit.Assert.*
assertTrue(condition)
assertFalse(condition)
assertEquals(expected, actual)
assertNotEquals(unexpected, actual)
assertNull(obj)
assertNotNull(obj)
assertSame(expected, actual)
assertNotSame(unexpected, actual)
fail(message)
```
--------------------------------
### Espresso Entry Point: onView()
Source: https://github.com/googlesamples/android-testing-templates/blob/master/_autodocs/api-reference/espresso-testing.md
The onView() method is the primary entry point for initiating interactions with views in Espresso tests. It requires an import from the Espresso library.
```kotlin
import android.support.test.espresso.Espresso.onView
```
--------------------------------
### Clone and Navigate Repository
Source: https://github.com/googlesamples/android-testing-templates/blob/master/_autodocs/QUICK_START.md
Clone or download the Android Testing Templates repository and navigate into the project directory. This is the initial step before opening the project in Android Studio.
```bash
# Clone or download the repository
cd android-testing-templates
```
--------------------------------
### Direct Instantiation of Module Classes
Source: https://github.com/googlesamples/android-testing-templates/blob/master/_autodocs/MODULE_ARCHITECTURE.md
Demonstrates how to create direct instances of classes from different modules within the main application module. This pattern is simple but leads to tight coupling.
```kotlin
// In app module (HelloTestingBlueprintActivity)
plainKotlinClassInstance = MyPlainKotlinClass()
androidLibraryClassInstance = AndroidLibraryModuleClass()
```
--------------------------------
### Check Module Readiness in Java
Source: https://github.com/googlesamples/android-testing-templates/blob/master/_autodocs/api-reference/android-library-module.md
Demonstrates how to instantiate and check the readiness of the AndroidLibraryModuleClass in Java. This is useful for verifying module initialization.
```java
AndroidLibraryModuleClass libraryModule = new AndroidLibraryModuleClass();
if (libraryModule.isReady()) {
// Use the library module
System.out.println("Library module is ready");
}
```
--------------------------------
### Run All Unit Tests with Gradle
Source: https://github.com/googlesamples/android-testing-templates/blob/master/_autodocs/api-reference/local-unit-testing.md
Execute all local unit tests for the project using the Gradle wrapper. This is the standard command to ensure all tests pass before further integration.
```bash
./gradlew test
```
--------------------------------
### Check Module Readiness in Kotlin
Source: https://github.com/googlesamples/android-testing-templates/blob/master/_autodocs/api-reference/android-library-module.md
Demonstrates how to instantiate and check the readiness of the AndroidLibraryModuleClass in Kotlin. This is useful for verifying module initialization.
```kotlin
val libraryModule = AndroidLibraryModuleClass()
if (libraryModule.isReady()) {
// Use the library module
println("Library module is ready")
}
```
--------------------------------
### EspressoTest
Source: https://github.com/googlesamples/android-testing-templates/blob/master/_autodocs/INDEX.md
Full Espresso testing reference, including test class declaration, ActivityTestRule setup, the `findViewPerformActionAndCheckAssertion` method, and details on Espresso components and patterns.
```APIDOC
## EspressoTest
### Description
UI testing implementation using Espresso.
### Test Class Declaration
Structure of the test class with `@RunWith` annotation.
### ActivityTestRule
Setup and management of `ActivityTestRule`.
### Test Method
- `findViewPerformActionAndCheckAssertion()`: Demonstrates the three-part Espresso pattern (find, perform, check).
### Espresso Components
Reference to Espresso entry points, matchers, actions, and assertions.
### Test Execution
Information on test execution and expected behavior.
### Dependencies
Required dependencies for Espresso testing.
### Common Patterns
Description of common Espresso patterns.
### Flavor-Specific Testing
Details on flavor-specific testing approaches.
```
--------------------------------
### Run Unit Tests
Source: https://github.com/googlesamples/android-testing-templates/blob/master/_autodocs/QUICK_START.md
Execute all local unit tests for the project using the Gradle wrapper.
```bash
# Run unit tests
./gradlew test
```
--------------------------------
### Run Instrumentation Tests via ADB
Source: https://github.com/googlesamples/android-testing-templates/blob/master/AndroidTestingBlueprint-kotlinApp/README.md
Execute instrumentation tests on a device or emulator using the adb shell am instrument command after installing the app and test app.
```bash
adb shell am instrument -w \
com.example.android.testing.blueprint.test/android.support.test.runner.AndroidJUnitRunner
```
--------------------------------
### Find, Click, and Verify Text with Espresso
Source: https://github.com/googlesamples/android-testing-templates/blob/master/_autodocs/api-reference/espresso-testing.md
Use this pattern to locate a UI element, perform a click action, and then assert that another element displays the expected text.
```kotlin
import androidx.test.espresso.Espresso.onView
import androidx.test.espresso.action.ViewActions.click
import androidx.test.espresso.assertion.ViewAssertions.matches
import androidx.test.espresso.matcher.ViewMatchers.withId
import androidx.test.espresso.matcher.ViewMatchers.withText
import org.junit.Test
@Test
fun clickButtonAndVerifyText() {
onView(withId(R.id.button))
.perform(click())
onView(withId(R.id.result))
.check(matches(withText("Result")))
}
```
--------------------------------
### Verify Mock Behavior with Mockito
Source: https://github.com/googlesamples/android-testing-templates/blob/master/_autodocs/api-reference/local-unit-testing.md
Demonstrates how to use Mockito to mock a class, define behavior for a method, and then assert that the method returns the expected value and was called.
```kotlin
import org.junit.Assert.assertEquals
import org.mockito.Mockito.*
@Test
fun verifyMockBehavior() {
val mock = mock(SomeClass::class.java)
mockWhen(mock.method()).thenReturn(value)
assertEquals(value, mock.method())
verify(mock).method()
}
```
--------------------------------
### Accessing Activity and String Resources
Source: https://github.com/googlesamples/android-testing-templates/blob/master/_autodocs/api-reference/espresso-testing.md
Demonstrates how to access the running activity instance and retrieve string resources using the ActivityTestRule.
```kotlin
val activity = activityRule.activity
val stringResource = activity.getString(R.string.android_testing_rocks)
```
--------------------------------
### Clean and Rebuild Project
Source: https://github.com/googlesamples/android-testing-templates/blob/master/_autodocs/QUICK_START.md
Use Gradle to clean the project and perform a full rebuild to resolve potential issues caused by corrupted build artifacts.
```bash
# Clean and rebuild
./gradlew clean build
```
--------------------------------
### Java Test Example Pattern
Source: https://github.com/googlesamples/android-testing-templates/blob/master/_autodocs/api-reference/android-library-module.md
This snippet demonstrates the equivalent test pattern for an Android library module in Java. It utilizes JUnit 4 and the AndroidX Test runner for instrumented testing.
```java
import android.support.test.runner.AndroidJUnit4;
import org.junit.Test;
import org.junit.runner.RunWith;
@RunWith(AndroidJUnit4.class)
public class AndroidLibraryModuleTest {
@Test
public void testIsReady() {
AndroidLibraryModuleClass instance = new AndroidLibraryModuleClass();
assertTrue(instance.isReady());
}
}
```
--------------------------------
### Run All Unit Tests (app module)
Source: https://github.com/googlesamples/android-testing-templates/blob/master/AndroidTestingBlueprint/README.md
Execute all local unit tests for the 'app' module using Gradle.
```sh
./gradlew app:test
```
--------------------------------
### Kotlin Test Example Pattern
Source: https://github.com/googlesamples/android-testing-templates/blob/master/_autodocs/api-reference/android-library-module.md
This snippet shows the standard pattern for writing an instrumented test for an Android library module in Kotlin. It uses JUnit 4 and the AndroidX Test runner.
```kotlin
import android.support.test.runner.AndroidJUnit4
import org.junit.Test
import org.junit.runner.RunWith
@RunWith(AndroidJUnit4::class)
class AndroidLibraryModuleTest {
@Test
fun testIsReady() {
val instance = AndroidLibraryModuleClass()
assert(instance.isReady())
}
}
```
--------------------------------
### Type Text and Verify with Espresso
Source: https://github.com/googlesamples/android-testing-templates/blob/master/_autodocs/api-reference/espresso-testing.md
This pattern demonstrates how to input text into an EditText view and then verify that the entered text is displayed correctly.
```kotlin
import androidx.test.espresso.Espresso.onView
import androidx.test.espresso.action.ViewActions.typeText
import androidx.test.espresso.assertion.ViewAssertions.matches
import androidx.test.espresso.matcher.ViewMatchers.withId
import androidx.test.espresso.matcher.ViewMatchers.withText
import org.junit.Test
@Test
fun typeTextAndVerify() {
onView(withId(R.id.editText))
.perform(typeText("input"))
onView(withId(R.id.editText))
.check(matches(withText("input")))
}
```
--------------------------------
### Main Application Module Source Sets
Source: https://github.com/googlesamples/android-testing-templates/blob/master/_autodocs/MODULE_ARCHITECTURE.md
Illustrates the directory structure for the main application module, including production code, resources, and various test source sets for different build variants and flavors.
```plaintext
app/src/
├── main/ # Common for all variants
│ ├── java/com/example/... # Production code
│ │ └── HelloTestingBlueprintActivity.kt
│ ├── res/ # Common resources
│ │ ├── layout/
│ │ ├── values/
│ │ └── drawable/
│ └── AndroidManifest.xml
│
├── test/ # Common local unit tests
│ ├── java/
│ │ └── LocalUnitTest.kt
│ └── resources/
│
├── testFlavor1/ # flavor1-specific unit tests
│ └── java/
│ └── LocalUnitTestForFlavor1.kt
│
├── androidTest/ # Common instrumented tests
│ ├── java/
│ │ ├── ui/espresso/EspressoTest.kt
│ │ ├── ui/uiautomator/UiAutomatorTest.kt
│ │ └── integration/AndroidLibraryModuleIntegrationTest.kt
│ └── AndroidManifest.xml
│
├── androidTestFlavor2/ # flavor2-specific instrumented tests
│ └── java/
│ └── ui/espresso/EspressoTestForFlavor2.kt
│
├── flavor1/ # flavor1-specific production code
│ ├── java/
│ │ └── Flavor1Class.kt
│ └── res/
│ └── values/strings.xml
│
└── flavor2/ # flavor2-specific production code
├── java/
└── res/
└── values/strings.xml
```
--------------------------------
### HelloTestingBlueprintActivity
Source: https://github.com/googlesamples/android-testing-templates/blob/master/_autodocs/DOCUMENTATION_SUMMARY.txt
Reference for the HelloTestingBlueprintActivity class, including its lifecycle methods, click handlers, and member variables.
```APIDOC
## HelloTestingBlueprintActivity
### Description
Reference for the HelloTestingBlueprintActivity class, covering its onCreate, onClick methods, and member variables.
### Methods
- **onCreate**
- **onClick**
### Member Variables
- [Details about member variables would be listed here if available in source]
### Source Location
- main-activity.md
```
--------------------------------
### Set Up Mock Behavior with Mockito (Java)
Source: https://github.com/googlesamples/android-testing-templates/blob/master/_autodocs/api-reference/local-unit-testing.md
Define the behavior of mock objects using `when`. This allows you to control the return values or exceptions thrown by mock methods.
```java
when(mock.method()).thenReturn(value);
when(mock.method()).thenThrow(new Exception());
```
--------------------------------
### Espresso UI Test for Android
Source: https://github.com/googlesamples/android-testing-templates/blob/master/_autodocs/TESTING_FRAMEWORKS.md
An example of an Espresso UI test using JUnit 4 and Android Testing Support Library. It finds a view, performs a click action, and checks for text assertion on an Android device or emulator.
```kotlin
@RunWith(AndroidJUnit4::class)
class EspressoTest {
@get:Rule
var activityRule = ActivityTestRule(HelloTestingBlueprintActivity::class.java)
@Test
fun findViewPerformActionAndCheckAssertion() {
// Find button and click
onView(withId(R.id.btn_hello_android_testing)).perform(click())
// Verify text displayed
onView(withId(R.id.text_view_rocks))
.check(matches(withText(
activityRule.activity.getString(R.string.android_testing_rocks))))
}
}
```
--------------------------------
### Run Integration Tests
Source: https://github.com/googlesamples/android-testing-templates/blob/master/_autodocs/QUICK_START.md
Execute instrumented integration tests that require an emulator or physical device.
```bash
# Run integration tests (requires emulator/device)
./gradlew connectedAndroidTest
```
--------------------------------
### Run All Instrumentation Tests (app module)
Source: https://github.com/googlesamples/android-testing-templates/blob/master/AndroidTestingBlueprint/README.md
Execute all instrumentation tests within the 'app' module using Gradle.
```sh
./gradlew app:connectedAndroidTest
```
--------------------------------
### Check APK Differences
Source: https://github.com/googlesamples/android-testing-templates/blob/master/_autodocs/QUICK_START.md
List the generated APK files to inspect differences between build variants.
```bash
# Check APK differences
ls -la app/build/outputs/apk/*/
```
--------------------------------
### Espresso Click and Verify Text
Source: https://github.com/googlesamples/android-testing-templates/blob/master/_autodocs/TESTING_FRAMEWORKS.md
This snippet demonstrates how to click a button and then verify that a TextView displays the expected text.
```kotlin
// Click and verify text
onView(withId(R.id.button)).perform(click())
onView(withId(R.id.textView)).check(matches(withText("Expected")))
```
--------------------------------
### JUnit, Mockito, and Hamcrest Imports (Java)
Source: https://github.com/googlesamples/android-testing-templates/blob/master/_autodocs/api-reference/local-unit-testing.md
Import necessary classes and functions for unit testing in Java.
```java
// JUnit
import org.junit.Test;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
// Mockito
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyNoMoreInteractions;
import static org.mockito.Mockito.when;
// Hamcrest
import static org.hamcrest.CoreMatchers.notNullValue;
import static org.hamcrest.MatcherAssert.assertThat;
// Standard library
import java.io.File;
```
--------------------------------
### Run Plain Kotlin Module Unit Tests via Gradle
Source: https://github.com/googlesamples/android-testing-templates/blob/master/AndroidTestingBlueprint-kotlinApp/README.md
Execute unit tests for a plain Kotlin module using the Gradle test task.
```bash
./gradlew module-plain-kotlin:test
```
--------------------------------
### Espresso Actions: click()
Source: https://github.com/googlesamples/android-testing-templates/blob/master/_autodocs/api-reference/espresso-testing.md
The click() action simulates a user click on a matched view. Ensure you import ViewActions to use this functionality.
```kotlin
import android.support.test.espresso.action.ViewActions.click
```
--------------------------------
### isReady Method
Source: https://github.com/googlesamples/android-testing-templates/blob/master/_autodocs/api-reference/android-library-module.md
Checks the readiness state of the AndroidLibraryModuleClass instance. This method is designed for testing and always returns true.
```APIDOC
## isReady()
### Description
Checks if the module instance is ready. This method is a simple readiness check and always returns `true`.
### Method Signature
```
public boolean isReady()
```
### Parameters
None
### Return Type
`boolean`
### Return Value
Always returns `true`.
### Example Usage
```java
AndroidLibraryModuleClass libraryModule = new AndroidLibraryModuleClass();
if (libraryModule.isReady()) {
System.out.println("Library module is ready");
}
```
```
--------------------------------
### Android Studio Keyboard Shortcuts (Linux/Windows)
Source: https://github.com/googlesamples/android-testing-templates/blob/master/_autodocs/QUICK_START.md
Common keyboard shortcuts for Android Studio on Linux and Windows. Includes actions for running tests, building, and debugging.
```text
| Action | Shortcut |
|--------|----------|
| Run Tests | Ctrl + Shift + F10 |
| Run Specific Test | Ctrl + Shift + F10 (on test) |
| Build Project | Ctrl + B |
| Run App | Shift + F10 |
| Debug App | Shift + F9 |
| Open File | Ctrl + O |
| Search Symbol | Ctrl + Alt + Shift + N |
```
--------------------------------
### Plain Kotlin Module Build Configuration
Source: https://github.com/googlesamples/android-testing-templates/blob/master/_autodocs/api-reference/plain-module-kotlin.md
The build.gradle file configuration for the plain Kotlin module, including Kotlin and test dependencies.
```gradle
apply plugin: 'kotlin'
dependencies {
compile "org.jetbrains.kotlin:kotlin-stdlib-jre7:$kotlinVersion"
testCompile 'junit:junit:' + rootProject.ext.junitVersion
testCompile 'org.hamcrest:hamcrest-core:' + rootProject.ext.hamcrestVersion
}
```
--------------------------------
### Build Specific Flavors
Source: https://github.com/googlesamples/android-testing-templates/blob/master/_autodocs/QUICK_START.md
Assemble debug versions of specific application flavors using Gradle.
```bash
# Try building different flavors
./gradlew assembleFlavor1Debug
./gradlew assembleFlavor2Debug
```
--------------------------------
### Gradle Settings File Configuration
Source: https://github.com/googlesamples/android-testing-templates/blob/master/_autodocs/BUILD_SYSTEM.md
Declares all submodules included in the Gradle build. Ensure each module is listed here to be recognized by the build system.
```gradle
include ':app'
include ':module-plain-kotlin' // or ':module-plain-java'
include ':module-android-library'
include ':module-flavor1-androidTest-only'
```
--------------------------------
### Root-Level Build Configuration (Kotlin)
Source: https://github.com/googlesamples/android-testing-templates/blob/master/_autodocs/BUILD_SYSTEM.md
Configures build script repositories, plugins, and global properties for Kotlin projects. Defines SDK versions and library dependencies.
```gradle
buildscript {
ext {
minSdkVersion = 14
targetSdkVersion = 27
compileSdkVersion = 27
kotlinVersion = "1.2.0"
supportLibVersion = "27.0.2"
junitVersion = "4.12"
mockitoVersion = "1.10.19"
hamcrestVersion = "1.3"
runnerVersion = "0.5"
rulesVersion = "0.5"
espressoVersion = "2.2.2"
uiautomatorVersion = "2.1.2"
}
repositories {
jcenter()
google()
}
dependencies {
classpath 'com.android.tools.build:gradle:3.0.1'
classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlinVersion"
}
}
allprojects {
repositories {
jcenter()
google()
}
}
```
--------------------------------
### Android Studio Gradle Sync
Source: https://github.com/googlesamples/android-testing-templates/blob/master/_autodocs/QUICK_START.md
Steps to ensure a successful Gradle sync in Android Studio after opening the project. Verify the build panel for any errors.
```text
After opening project:
1. Wait for Gradle sync (automatic)
2. Verify no errors in "Build" panel
3. Project should appear in "Project" panel with all modules
```
--------------------------------
### Java App Directory Structure
Source: https://github.com/googlesamples/android-testing-templates/blob/master/_autodocs/PROJECT_OVERVIEW.md
Presents the parallel directory structure for the Java version of the Android Testing Blueprint project, mirroring the organization of the Kotlin version.
```text
AndroidTestingBlueprint/ # Java version (parallel structure)
├── app/
├── module-plain-java/
├── module-android-library/
└── module-flavor1-androidTest-only/ # Flavor-specific test module
```
--------------------------------
### Verify Emulator Visibility
Source: https://github.com/googlesamples/android-testing-templates/blob/master/_autodocs/QUICK_START.md
Use adb devices -l to verify that the emulator is visible to ADB and to check its detailed information.
```bash
# Verify emulator is visible
```
```bash
adb devices -l
```
--------------------------------
### Root-Level Build Configuration (Java)
Source: https://github.com/googlesamples/android-testing-templates/blob/master/_autodocs/BUILD_SYSTEM.md
Configures build script repositories and plugins for Java projects. Defines SDK versions and library dependencies.
```gradle
buildscript {
repositories {
jcenter()
google()
}
dependencies {
classpath 'com.android.tools.build:gradle:3.0.1'
}
}
allprojects {
repositories {
jcenter()
google()
}
}
ext {
minSdkVersion = 14
targetSdkVersion = 27
compileSdkVersion = 27
supportLibVersion = "27.0.1"
junitVersion = "4.12"
mockitoVersion = "1.10.19"
hamcrestVersion = "1.3"
runnerVersion = "0.5"
rulesVersion = "0.5"
espressoVersion = "2.2.2"
uiautomatorVersion = "2.1.2"
}
```
--------------------------------
### Kotlin App Directory Structure
Source: https://github.com/googlesamples/android-testing-templates/blob/master/_autodocs/PROJECT_OVERVIEW.md
Illustrates the standard directory layout for the Kotlin version of the Android Testing Blueprint application, including production code, test directories, and flavor-specific modules.
```text
AndroidTestingBlueprint-kotlinApp/
├── app/ # Main application module
│ ├── src/main/ # Production code
│ ├── src/test/ # Local unit tests
│ ├── src/androidTest/ # Instrumented tests
│ └── src/flavor1/ # Flavor-specific code
├── module-plain-kotlin/ # Pure Kotlin module
├── module-android-library/ # Android library module
└── module-flavor1-androidTest-only/ # Flavor-specific test module
```
--------------------------------
### Main Application Module Build Configuration
Source: https://github.com/googlesamples/android-testing-templates/blob/master/_autodocs/BUILD_SYSTEM.md
Configures the main Android application module, including SDK versions, application ID, build types, product flavors, and test options. This file applies the 'com.android.application' plugin and optionally Kotlin plugins.
```gradle
apply plugin: 'com.android.application'
apply plugin: 'kotlin-android' // Kotlin version only
apply plugin: 'kotlin-android-extensions' // Kotlin version only
android {
compileSdkVersion rootProject.ext.compileSdkVersion
defaultConfig {
minSdkVersion rootProject.ext.minSdkVersion
targetSdkVersion rootProject.ext.targetSdkVersion
applicationId 'com.example.android.testing.blueprint'
versionCode 1
versionName '1.0'
testInstrumentationRunner 'android.support.test.runner.AndroidJUnitRunner'
testInstrumentationRunnerArguments disableAnalytics: 'true' // Optional
}
buildTypes {
debug {
testCoverageEnabled = true // Code coverage on debug builds
}
release {
minifyEnabled true
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
}
flavorDimensions "defaultDimension"
productFlavors {
flavor1 {
applicationId 'com.example.android.testing.blueprint.flavor1'
}
flavor2 {
applicationId 'com.example.android.testing.blueprint.flavor2'
}
}
testOptions.unitTests.all {
testLogging {
events 'passed', 'skipped', 'failed', 'standardOut', 'standardError'
}
}
}
```
--------------------------------
### Main Activity Layout XML
Source: https://github.com/googlesamples/android-testing-templates/blob/master/_autodocs/RESOURCE_ORGANIZATION.md
Defines the UI layout for the HelloTestingBlueprintActivity, including buttons and text views.
```xml
```
--------------------------------
### Find and Click Button with Espresso
Source: https://github.com/googlesamples/android-testing-templates/blob/master/_autodocs/api-reference/espresso-testing.md
Finds a button by its resource ID and performs a click action. Use this to simulate user interaction with buttons.
```kotlin
onView(withId(R.id.btn_hello_android_testing)).perform(click())
```
```java
Espresso.onView(ViewMatchers.withId(R.id.btn_hello_android_testing))
.perform(ViewActions.click());
```
--------------------------------
### Mockito Verification Patterns
Source: https://github.com/googlesamples/android-testing-templates/blob/master/_autodocs/TESTING_FRAMEWORKS.md
Shows how to verify interactions with mock objects, including method calls, call counts, order, and ensuring no extraneous calls.
```kotlin
// Verify method called
verify(mock).method()
// Verify method called N times
verify(mock, times(2)).method()
// Verify method never called
verify(mock, never()).method()
// Verify no other interactions
verifyNoMoreInteractions(mock)
// Verify call order
inOrder(mock1, mock2).verify(mock1).method1()
inOrder(mock1, mock2).verify(mock2).method2()
```
--------------------------------
### Run Instrumentation Tests (adb)
Source: https://github.com/googlesamples/android-testing-templates/blob/master/AndroidTestingBlueprint/README.md
Execute instrumentation tests for a specific package using the 'adb shell am instrument' command.
```sh
adb shell am instrument -w com.example.android.testing.blueprint.flavor2.test/android.support.test.runner.AndroidJUnitRunner
```
--------------------------------
### Referencing Resources in AndroidManifest.xml
Source: https://github.com/googlesamples/android-testing-templates/blob/master/_autodocs/RESOURCE_ORGANIZATION.md
Illustrates how to use resource references, such as strings and drawables, within the application and activity elements of the AndroidManifest.xml file.
```xml
```
--------------------------------
### Local Unit Test with Mockito and Hamcrest
Source: https://github.com/googlesamples/android-testing-templates/blob/master/_autodocs/TESTING_FRAMEWORKS.md
Demonstrates mocking final classes and loading test data from resources using JUnit 4, Mockito, and Hamcrest. Suitable for fast, JVM-only tests.
```kotlin
class LocalUnitTest {
@Test
fun mockFinalClass() {
val adapter = mock(BluetoothAdapter::class.java)
mockWhen(adapter.isEnabled).thenReturn(true)
assertTrue(adapter.isEnabled)
verify(adapter).isEnabled
verifyNoMoreInteractions(adapter)
}
@Test
fun loadTestDataFromResources() {
val testFile = File(javaClass.getResource("/helloBlueprint.json").path)
assertThat(testFile, notNullValue())
}
}
```
--------------------------------
### Inspect UI Test Code
Source: https://github.com/googlesamples/android-testing-templates/blob/master/_autodocs/QUICK_START.md
Locate the file containing the project's UI (Espresso) tests.
```bash
# View UI tests
# app/src/androidTest/java/ui/espresso/EspressoTest.kt
```
--------------------------------
### LocalUnitTest
Source: https://github.com/googlesamples/android-testing-templates/blob/master/_autodocs/INDEX.md
Comprehensive reference for JUnit unit testing with Mockito and Hamcrest, covering test class structure, mocking final methods/classes, loading test fixtures, and references to Mockito, JUnit, and Hamcrest.
```APIDOC
## LocalUnitTest
### Description
JUnit unit testing with Mockito and Hamcrest.
### Test Class Structure
Details on the structure of unit test classes.
### Mocking
- `mockFinalMethod()`: Demonstrates mocking final methods.
- `mockFinalClass()`: Demonstrates mocking final Android classes.
### Test Fixtures
- `loadTestDataFromResources()`: Method for loading test fixtures from resources.
### Mockito Reference
Reference for Mockito features including mock creation, behavior setup, and verification.
### JUnit Assertions
Reference for JUnit 4 assertions.
### Hamcrest Matchers
Reference for Hamcrest matchers.
### Test Execution
Information on running tests and execution flow.
### Test Isolation
Details on test isolation.
### Comparison with Instrumented Tests
Comparison between local unit tests and instrumented tests.
### Best Practices
Recommended best practices for unit testing.
```
--------------------------------
### Set Up Mock Behavior with Mockito (Kotlin)
Source: https://github.com/googlesamples/android-testing-templates/blob/master/_autodocs/api-reference/local-unit-testing.md
Define the behavior of mock objects using `mockWhen`. This allows you to control the return values or exceptions thrown by mock methods.
```kotlin
mockWhen(mock.method()).thenReturn(value)
mockWhen(mock.method()).thenThrow(Exception())
mockWhen(mock.property).thenReturn(value)
```
--------------------------------
### Core Testing Framework Dependencies
Source: https://github.com/googlesamples/android-testing-templates/blob/master/_autodocs/api-reference/local-unit-testing.md
Add these dependencies to your module's build.gradle file to include JUnit, Mockito, and Hamcrest for local unit tests.
```gradle
testImplementation 'junit:junit:4.12'
testImplementation 'org.mockito:mockito-all:1.10.19'
testImplementation 'org.hamcrest:hamcrest-all:1.3'
```
--------------------------------
### Local Unit Test with Mockito
Source: https://github.com/googlesamples/android-testing-templates/blob/master/_autodocs/QUICK_START.md
Demonstrates mocking an Android Activity and verifying method calls using Mockito in a local unit test. This snippet is suitable for testing logic that doesn't require an Android device or emulator.
```kotlin
import org.junit.Test
import org.mockito.Mockito.*
import org.mockito.Mockito.mock
import org.mockito.Mockito.verify
import org.mockito.Mockito.when as mockWhen
import org.junit.Assert.assertFalse
import android.app.Activity
@Test
fun testMocking() {
val mock = mock(Activity::class.java)
mockWhen(mock.isFinishing).thenReturn(false)
assertFalse(mock.isFinishing)
verify(mock).isFinishing
}
```
--------------------------------
### Espresso and JUnit Imports for Testing
Source: https://github.com/googlesamples/android-testing-templates/blob/master/_autodocs/api-reference/espresso-testing.md
Essential imports for writing Espresso UI tests, including Espresso APIs, JUnit rules, and test runners.
```kotlin
// Test infrastructure
import android.support.test.espresso.Espresso.onView
import android.support.test.espresso.action.ViewActions.click
import android.support.test.espresso.assertion.ViewAssertions.matches
import android.support.test.espresso.matcher.ViewMatchers.withId
import android.support.test.espresso.matcher.ViewMatchers.withText
import android.support.test.rule.ActivityTestRule
import android.support.test.runner.AndroidJUnit4
// JUnit
import org.junit.Rule
import org.junit.Test
import org.junit.runner.RunWith
// Project classes
import com.example.android.testing.blueprint.HelloTestingBlueprintActivity
import com.example.android.testing.blueprint.R
```
--------------------------------
### Accessing Resources from Kotlin Code
Source: https://github.com/googlesamples/android-testing-templates/blob/master/_autodocs/RESOURCE_ORGANIZATION.md
Demonstrates how to retrieve string, dimension, color, and view resources within Kotlin code. Use `getString`, `resources.getDimension`, `getColor` (API 23+), and `findViewById`.
```kotlin
// String resource
val text = getString(R.string.android_testing_rocks)
// Dimension resource (in pixels)
val margin = resources.getDimension(R.dimen.activity_horizontal_margin).toInt()
// Color resource
val color = getColor(R.color.primary_color) // API 23+
// View reference
val button = findViewById