核心本机测试

写作 社区

技能解读

当前原文的自动摘译,尚未人工审校。

概述

此技能指导为packages/bcsc-core模块创建本机单元测试,该模块包含身份验证、PIN 管理、钥匙串存储、令牌服务和设备身份验证的 Swift (iOS) 和 Kotlin (Android) 实现。该代码库已经在 iOS 上使用基于协议的依赖注入,在 Android 上使用基于接口/类的注入,从而可以轻松地为隔离单元测试创​​建模拟实现。

iOS — 通过 SPM 的 XCTest

测试是使用 Swift Package Manager 使用 packages/bcsc-core/Package.swift 处的包清单构建的。关键概念: BcscCoreTestable 目标:为模拟器编译的生产 iOS 源文件的子集(没有 React Native / CocoaPods 依赖项)。仅包含 sources: 数组中列出的文件。 BcscCoreTests测试目标:ios/BcscCoreTests/下的XCTest文件,使用@testable import BcscCoreTestable编译。

Android — JUnit 4 + MockK

在镜像主源包结构的android/src/test/java/com/bcsccore/下进行测试。依赖关系(在android/build.gradle中) 添加新的Android测试文件 在android/src/test/java/com/bcsccore/{subpackage}/中创建一个Kotlin文件,与源码包匹配。使用 @Test 方法编写标准 JUnit 4 测试类。

iOS——协议一致性

代码库定义了所有服务边界的协议。创建符合协议并公开可控属性的模拟类: 模式:使用 var resultProperty 控制返回值,使用 var methodCalled = false 布尔值验证副作用。可用于模拟的 iOS 协议 协议 · 文件 · 目的 PINServiceProtocol · PINServiceProtocol.swift · PIN 设置/验证/删除/哈希

Android——MockK

使用 MockK 的 mockk<T>() 来模拟类和接口:对于数据类(例如 NativeAccount),直接使用 Gson 测试序列化往返 - 无需模拟。

流狐档案 运行与权限由流狐静态检查推断,不代表作者声明或实际测试结果。
领域
写作
作者声明的智能体
未找到明确声明;不据此推断已兼容或已测试
静态检查
88 / 100 · 启发式扫描,不代表运行安全
运行环境证据
未执行;当前没有隔离运行测试证据
作者 / 版本 / 许可证
@tomevault-io · 未声明许可证
上下文用量评级
低消耗
接入复杂程度
即装即用
是否需要外部接口密钥
不需要
兼容的系统
未声明(默认跨平台)
运行环境要求
未检出明确要求
检测到的文件与系统行为
  • 只读
  • 允许写入 / 修改
网络行为
仅限本地
安装命令数
无(仅作为资料)

需要注意: 未声明工具权限范围;实际权限由运行环境决定。

作者说明文件(原文) SKILL.md

# bcsc-core Native Unit Testing

## Overview

This skill guides creation of native unit tests for the `packages/bcsc-core` module, which contains Swift (iOS) and Kotlin (Android) implementations of authentication, PIN management, keychain storage, token services, and device authentication.

The codebase already uses **protocol-based dependency injection** on iOS and **interface/class-based injection** on Android, making it straightforward to create mock implementations for isolated unit testing.

## Test Infrastructure

### iOS — XCTest via SPM

Tests are built with Swift Package Manager using the package manifest at `packages/bcsc-core/Package.swift`. The key concepts:

- **`BcscCoreTestable` target**: A subset of production iOS source files compiled for the simulator (without React Native / CocoaPods dependencies). Only files listed in the `sources:` array are included.
- **`BcscCoreTests` test target**: XCTest files under `ios/BcscCoreTests/`, compiled with `@testable import BcscCoreTestable`.
- **`SPM_BUILD` flag**: A Swift compiler define set in `Package.swift` via `swiftSettings: [.define("SPM_BUILD")]`. The file `ios/SPMCompat.swift` uses `#if SPM_BUILD` to provide lightweight stubs (e.g., `SecureRandom`, `Data.arrayOfBytes()`) for types from JWE files that aren't included in the SPM target.
- **Scheme name**: xcodebuild uses `BcscCoreTests-Package` (SPM auto-appends `-Package`).

#### Adding a new iOS source file to the test target

If the code under test references types in a file not yet in `Package.swift`, add it to the `sources:` array in the `BcscCoreTestable` target. If that file depends on types from excluded files (e.g., JWE/crypto), add stubs to `SPMCompat.swift` behind `#if SPM_BUILD`.

#### Adding a new iOS test file

1. Create a new `.swift` file in `ios/BcscCoreTests/`.
2. Import frameworks and the testable module:
   ```swift
   import LocalAuthentication  // if testing LAPolicy/biometric types
   import XCTest
   @testable import BcscCoreTestable
   ```
3. Write `XCTestCase` subclasses. Follow the naming convention `{ClassUnderTest}Tests`.
4. Run with `yarn test:ios` or directly:
   ```sh
   xcodebuild test -scheme BcscCoreTests-Package \
     -destination 'platform=iOS Simulator,name=iPhone 16,OS=latest' \
     -skipPackagePluginValidation
   ```

### Android — JUnit 4 + MockK

Tests live under `android/src/test/java/com/bcsccore/` mirroring the main source package structure.

#### Dependencies (in `android/build.gradle`)

```groovy
testImplementation 'junit:junit:4.13.2'
testImplementation 'io.mockk:mockk:1.13.8'
testImplementation 'org.robolectric:robolectric:4.11.1'
testImplementation 'androidx.test:core:1.5.0'
```

#### Adding a new Android test file

1. Create a Kotlin file in `android/src/test/java/com/bcsccore/{subpackage}/`, matching the source package.
2. Write standard JUnit 4 test classes with `@Test` methods.
3. Use `io.mockk.mockk<T>()` and `every { ... } returns ...` for mocking.
4. Run with `yarn test:android` or directly:
   ```sh
   cd android && ./gradlew test
   ```

### Running all tests

```sh
yarn test          # runs test:ios then test:android
yarn test:ios      # iOS only
yarn test:android  # Android only
```

## Mocking Strategy

### iOS — Protocol Conformance

The codebase defines protocols for all service boundaries. Create mock classes that conform to the protocol and expose controllable properties:

```swift
final class MockPINService: PINServiceProtocol {
    var verifyResult: String?        // control return value
    var setPINResult: String = "mock-hash"
    var deletePINCalled = false      // track side effects

    func verifyPINAndGetHash(issuer _: String, accountID _: String, pin _: String) -> String? {
        return verifyResult
    }

    func setPIN(issuer _: String, accountID _: String, pin _: String, isAutoGenerated _: Bool) throws -> String {
        return setPINResult
    }

    func deletePIN(issuer _: String, accountID _: String) throws {
        deletePINCalled = true
    }
    // ... remaining protocol methods
}
```

**Pattern**: Use `var resultProperty` for controlling return values and `var methodCalled = false` booleans for verifying side effects.

#### Available iOS protocols for mocking

| Protocol                      | File                         | Purpose                    |
| ----------------------------- | ---------------------------- | -------------------------- |
| `PINServiceProtocol`          | `PINServiceProtocol.swift`   | PIN set/verify/delete/hash |
| `PINKeychainServiceProtocol`  | `PINKeychainService.swift`   | Keychain secret storage    |
| `PINCryptoPolicyProtocol`     | `PINCryptoPolicy.swift`      | Salt/key/iteration config  |
| `CommonCryptoWrapperProtocol` | `CommonCryptoWrapper.swift`  | PBKDF2 key derivation      |
| `LAContextProtocol`           | `LAContext+Extensions.swift` | Biometric evaluation       |
| `DeviceAuthServiceProtocol`   | `DeviceAuthService.swift`    | Device authentication      |
| `TokenStorageServiceProtocol` | `TokenService.swift`         | Token keychain storage     |
| `KeyPairManagerProtocol`      | `KeyPairManager.swift`       | Cryptographic key pairs    |

### Android — MockK

Use MockK's `mockk<T>()` for mocking classes and interfaces:

```kotlin
val mockPinService = mockk<PinService>()
every { mockPinService.validatePIN(any(), "1234") } returns true
every { mockPinService.hasPIN(any()) } returns true

val account = Account(id = "test", issuer = "https://idsit.gov.bc.ca", clientID = "client")
val result = account.verifyPIN("1234", mockPinService)
assertTrue(result.success)
```

For data classes (e.g., `NativeAccount`), test serialization round-trips with Gson directly — no mocking needed.

## Test Patterns

### Time-dependent tests (eg. PIN penalty logic)

The penalty system locks users out after failed PIN attempts. Both platforms accept an injectable "current time" parameter to make tests deterministic.

**iOS**: Pass `verifyDate:` parameter:

```swift
let start = Date()
for i in 0..<5 {
    _ = account.verifyPIN("wrong", pinService: mock, verifyDate: start.addingTimeInterval(Double(i)))
}
// Advance past penalty before next batch
let afterPenalty = start.addingTimeInterval(65)
```

**Android**: Pass timestamp to `verifyPIN` and `isServingPenalty`:

```kotlin
val now = System.currentTimeMillis()
account.verifyPIN("wrong", mockPinService, now)
val penalty = account.isServingPenalty(now)
```

**Important**: When testing escalating penalties, you must advance time past each penalty tier before triggering the next. Calling `verifyPIN` while a penalty is active will return "locked" without incrementing the attempt counter.

Penalty tiers: 5 attempts → 1 min, 10 → 10 min, 15 → 1 hour, 20 → 1 day.

### NSCoding / Serialization round-trips

**iOS** — Use `NSKeyedArchiver` / `NSKeyedUnarchiver`:

```swift
let data = try NSKeyedArchiver.archivedData(withRootObject: original, requiringSecureCoding: true)
let decoded = try NSKeyedUnarchiver.unarchivedObject(ofClass: Account.self, from: data)
XCTAssertEqual(decoded?.id, original.id)
```

**Android** — Use Gson:

```kotlin
val json = gson.toJson(original)
val restored = gson.fromJson(json, NativeAccount::class.java)
assertEquals(original.uuid, restored.uuid)
```

### Test naming conventions

**iOS**: `test{Behavior}` in camelCase — e.g., `testVerifyPINReturnsSuccessOnCorrectPIN`
**Android**: Backtick-quoted descriptive names — e.g., `` `verifyPIN returns success when PIN is correct` ``

### Helper factories

**Android** — Create a `createAccount()` helper with defaults to reduce boilerplate:

```kotlin
private fun createAccount(
    id: String = "test-uuid",
    issuer: String = "https://idsit.gov.bc.ca",
    clientID: String = "test-client-id",
    securityMethod: AccountSecurityMethod = AccountSecurityMethod.PIN_NO_DEVICE_AUTH,
): Account = Account(id = id, issuer = issuer, clientID = clientID, securityMethod = securityMethod)
```

## Checklist for adding tests

- [ ] Identify the class/struct to test and which platform(s)
- [ ] Check if the source file is already in `Package.swift` `sources:` (iOS) — add if missing
- [ ] Check if new dependencies need stubs in `SPMCompat.swift` (iOS)
- [ ] Create mock(s) for any protocol/interface dependencies
- [ ] Place test file in `ios/BcscCoreTests/` or `android/src/test/java/com/bcsccore/{subpackage}/`
- [ ] For time-dependent logic, use injectable timestamps rather than `Date()` / `System.currentTimeMillis()`
- [ ] Run `yarn test` and verify all tests pass on both platforms

---
> Source: [bcgov/bc-wallet-mobile](https://github.com/bcgov/bc-wallet-mobile) — distributed by [TomeVault](https://tomevault.io).
<!-- tomevault:4.0:skill_md:2026-05-23 -->

讨论

基于 GitHub Discussions。登录 GitHub 即可参与讨论、点赞、订阅更新。