# Testing and Debugging

Relevant source files

- [dokka.gradle](https://github.com/FrontFin/mesh-android-sdk/blob/e01c1f6c/dokka.gradle)
- [link/src/debug/kotlin/hepler/DebugWebViewClient.kt](https://github.com/FrontFin/mesh-android-sdk/blob/e01c1f6c/link/src/debug/kotlin/hepler/DebugWebViewClient.kt)
- [link/src/test/kotlin/com/meshconnect/link/entity/DelayedAuthPayloadTest.kt](https://github.com/FrontFin/mesh-android-sdk/blob/e01c1f6c/link/src/test/kotlin/com/meshconnect/link/entity/DelayedAuthPayloadTest.kt)

This document covers testing strategies, debugging techniques, and development tools for the Mesh Connect Android SDK. It provides guidance for SDK developers working on the codebase and application developers integrating the SDK into their Android applications.

For information about SDK configuration and setup, see [Getting Started](/content/FrontFin/mesh-android-sdk/2-getting-started/index.html). For details about the core architecture and communication systems, see [Core Architecture](/content/FrontFin/mesh-android-sdk/3-core-architecture/index.html).

## Debug WebView Client

The SDK includes a comprehensive debug WebView client that provides detailed logging for all WebView interactions during development. The `DebugWebViewClient` class intercepts and logs all WebView lifecycle events, network requests, and errors.

```
WebView
DebugWebViewClient
Logging Methods
shouldOverrideUrlLoading()
onPageStarted()/onPageFinished()
shouldInterceptRequest()
onReceivedError()/onReceivedHttpError()
onReceivedSslError()
onReceivedHttpAuthRequest()
Android Log Output
```

### Key Debug Events

The debug client logs the following critical events:

| Event Type       | Method                                   | Purpose                                |
| ---------------- | ---------------------------------------- | -------------------------------------- |
| URL Navigation   | `shouldOverrideUrlLoading()`            | Track URL changes and redirects        |
| Page Lifecycle    | `onPageStarted()`, `onPageFinished()` | Monitor page loading states            |
| Resource Loading  | `onLoadResource()`, `shouldInterceptRequest()` | Debug network requests          |
| Error Handling    | `onReceivedError()`, `onReceivedHttpError()` | Identify loading failures          |
| Security Events   | `onReceivedSslError()`, `onReceivedClientCertRequest()` | Debug SSL/TLS issues           |

All debug output is tagged with "DebugWebViewClient" and can be filtered using Android Studio's logcat:

```
adb logcat -s DebugWebViewClient
```

**Sources:** [link/src/debug/kotlin/hepler/DebugWebViewClient.kt1-187](https://github.com/FrontFin/mesh-android-sdk/blob/e01c1f6c/link/src/debug/kotlin/hepler/DebugWebViewClient.kt#L1-L187)

## Unit Testing Framework

The SDK employs a structured unit testing approach using JUnit and MockK for testing individual components and data structures.

```
Test Classes

Entity Tests
Use Case Tests
Utility Tests
DelayedAuthPayloadTest
Data Model Validation
Message Processing Tests
Broadcast Logic Tests
JSON Serialization Tests
Helper Function Tests

Test Libraries
JUnit 4/5
MockK
Kluent Assertions
```

### Entity Testing Pattern

The SDK uses a consistent pattern for testing data entities:

```kotlin
// Example pattern from DelayedAuthPayloadTest
@Test
fun `test entity creation and property access`() {
    // Arrange - create test data
    val property1 = randomValue
    val property2 = mockk<DependentEntity>()

// Act - create entity
    val entity = EntityUnderTest(property1, property2)

// Assert - verify properties
    assertEquals(property1, entity.property1)
    assertEquals(property2, entity.property2)
}
```

### Test Utilities

The SDK provides test utilities for generating random test data:

- `randomInt` - generates random integer values
- `randomString` - generates random string values
- `mockk<T>()` - creates mock objects for dependencies

**Sources:** [link/src/test/kotlin/com/meshconnect/link/entity/DelayedAuthPayloadTest.kt1-33](https://github.com/FrontFin/mesh-android-sdk/blob/e01c1f6c/link/src/test/kotlin/com/meshconnect/link/entity/DelayedAuthPayloadTest.kt#L1-L33)

## Integration Testing

Integration testing focuses on testing the SDK's integration with host Android applications and the complete WebView communication flow.

```
"Test Backend" "JSBridge" "WebView" "LinkActivity" "Test Application"
"End-to-end flow validation" "Request test linkToken" "Mock linkToken response"
"launch(testConfiguration)" "load test web content" "send test JSON messages"
"process test events" "return test results"
```

### Test Configuration Setup

Integration tests require proper configuration setup:

```kotlin
// Test LinkConfiguration setup
val testConfig = LinkConfiguration(
    linkToken = "test_link_token_12345",
    accessTokens = emptyMap(),
    settings = LinkSettings(
        colors = testColorScheme,
        companyName = "Test Company"
    )
)
```

### WebView Communication Testing

Testing the WebView-to-native communication bridge:
1. **Message Serialization Tests** - Verify JSON message formatting
2. **Event Processing Tests** - Validate event handling logic
3. **Payload Deserialization Tests** - Ensure proper data structure creation
4. **Error Handling Tests** - Test error scenarios and recovery

**Sources:** Inferred from architecture diagrams and testing patterns

## WebView Communication Debugging

Debugging the communication between WebView content and native Android code requires monitoring the JavaScript bridge and message processing pipeline.

```
Web Content
@JavascriptInterface methods
Message Processing Pipeline
DeserializeLinkMessageUseCase
BroadcastLinkMessageUseCase
LinkEvents
LinkPayloads
FilterLinkMessage
Debug Points
JS Interface Logging
Message Content Logging
Deserialization Logging
Event Emission Logging
```

### Debug Strategies

1. **JavaScript Console Logging** - Add console.log statements in web content
2. **Native Method Logging** - Log all `@JavascriptInterface` method calls
3. **Message Content Inspection** - Log raw JSON messages before processing
4. **Event Flow Tracing** - Track events from reception to emission

### Common Debug Scenarios

| Scenario                    | Debug Approach                     | Key Checkpoints               |
| --------------------------- | ---------------------------------- | ----------------------------- |
| Messages not received       | Check WebView client setup        | JSBridge registration         |
| Parsing failures            | Validate JSON structure           | Deserialization logic         |
| Events not emitted          | Verify event processing            | Broadcasting pipeline         |
| Incorrect payloads          | Check type mapping                | Payload construction          |

**Sources:** Inferred from [WebView Communication](/content/FrontFin/mesh-android-sdk/3.1-webview-communication/index.html) and [Message Broadcasting System](/content/FrontFin/mesh-android-sdk/3.2-message-broadcasting-system/index.html)

## Logging and Monitoring

The SDK implements comprehensive logging for monitoring runtime behavior and diagnosing issues in production environments.

```
Logging Sources
DebugWebViewClient
JSBridge Logging
Message Processing Logging
Error Handling Logging
Page events, URL changes, Errors
Method calls, Message content
Deserialization, Broadcasting
Exception details, Stack traces
Log Output
Android Log (Logcat)
Crash Reporting Systems
Log Analysis Tools
Error Tracking Platforms
```

### Log Tags and Levels

The SDK uses consistent log tags for filtering:

- `DebugWebViewClient` - WebView lifecycle and network events
- `JSBridge` - JavaScript-native communication (inferred)
- `LinkViewModel` - Message processing and state management (inferred)
- `LinkActivity` - Activity lifecycle and user interactions (inferred)

### Production Logging Considerations

- Debug-level logging is only available in debug builds
- Production builds include essential error logging
- Sensitive data (tokens, user information) is not logged
- Performance impact of logging is minimized

**Sources:** [link/src/debug/kotlin/hepler/DebugWebViewClient.kt19](https://github.com/FrontFin/mesh-android-sdk/blob/e01c1f6c/link/src/debug/kotlin/hepler/DebugWebViewClient.kt#L19-L19)

## Documentation and Code Coverage

The SDK includes automated documentation generation and code coverage reporting as part of the development and testing workflow.

```
Development Tools
Dokka Documentation
JaCoCo Coverage
Quality Gates
API Documentation
Module Documentation
Coverage Reports
Coverage Metrics
SonarQube Analysis
Static Analysis
CI Process
Automated Testing
Quality Validation
Unit Tests
Integration Tests
Code Style Checks
Security Analysis
```

### Documentation Generation

The Dokka configuration generates comprehensive API documentation:
- **Module Name**: `mesh-android-sdk`
- **Inherited Members**: Suppressed for cleaner documentation
- **Output Format**: HTML documentation
- **Coverage**: All public APIs and data structures

### Testing and Coverage Pipeline

The CI/CD pipeline enforces quality standards:
1. **Unit Test Execution** - All test suites must pass
2. **Coverage Analysis** - Minimum coverage thresholds enforced
3. **Static Analysis** - Code quality and security checks
4. **Documentation Build** - API documentation generation

### Debug Build Features

Debug builds include additional testing and debugging capabilities:
- Enhanced WebView logging via `DebugWebViewClient`
- Detailed message processing logs
- Development-only debugging utilities
- Extended error reporting and stack traces

**Sources:** [dokka.gradle1-5](https://github.com/FrontFin/mesh-android-sdk/blob/e01c1f6c/dokka.gradle#L1-L5)
