本文へ移動
cccskills
無料GitHub で公開

mock-call-count-retry-fallback

Fix test failures when adding retry/fallback logic causes mock call count mismatches. Use when: (1) Test fails with "Expected: <1>, Actual: <2>" or similar call count errors after adding retry or fallback mechanisms, (2) MissingStubError appears for methods in new fallback code paths, (3) Mockito verify().called(N) assertions fail after behavior changes. Applies to Dart/Flutter with Mockito, but pattern is universal.

インストール方法を見る

含まれるファイル(1)

  • SKILL.md4.8 KB

SKILL.md(原文)

インストールする前に、エージェントに与えられる指示の中身を確認できます。

Mock Call Count Failures After Adding Retry/Fallback Logic

Problem

When you add retry logic, fallback mechanisms, or alternative code paths to a service, existing tests that verify exact mock method call counts will fail. The tests were written for the original behavior and don't account for the new retry/fallback calls.

Context / Trigger Conditions

  • Test fails with: Expected: <N>, Actual: <M> where M > N
  • Error message: "Unexpected number of calls"
  • MissingStubError: 'methodName' No stub was found which matches the arguments
  • You recently added:
    • Retry logic (e.g., retry after timeout)
    • Fallback mechanisms (e.g., try primary server, fall back to secondary)
    • Alternative code paths (e.g., try REST API, fall back to WebSocket)
  • The failing test uses verify(...).called(N) assertions

Solution

Step 1: Identify the New Code Paths

Trace through your new retry/fallback logic to understand:

  • How many times the mocked method will now be called
  • What new methods are being called that weren't before

Step 2: Mock New Dependencies

If your fallback code calls methods that weren't previously mocked:

// BEFORE: Only mocked the primary method
when(mockService.primaryMethod(any)).thenAnswer((_) async => 'result');

// AFTER: Also mock fallback-related methods
when(mockService.primaryMethod(any)).thenAnswer((_) async => 'result');
when(mockService.addFallbackServer(any)).thenAnswer((_) async => false);  // Graceful failure
when(mockService.queryFallback(any)).thenAnswer((_) async => []);

Step 3: Update Expected Call Counts

// BEFORE: Expected single call
verify(mockService.createSubscription(...)).called(1);

// AFTER: Expected calls = initial + retries
// Document WHY the count changed
verify(mockService.createSubscription(...)).called(2);  // initial + retry after fallback

Step 4: Add Comments Explaining the Count

// Verify subscription was created
// Note: With the indexer fallback logic, createSubscription is called twice:
// 1. First attempt via main relay batch fetch
// 2. Retry attempt after indexer fallback fails
verify(
  mockService.createSubscription(...),
).called(2);

Verification

  1. Run the specific test: flutter test --name "test name"
  2. Verify the test passes
  3. Verify the service's actual behavior matches the expected retry count

Example

Scenario: Added indexer relay fallback to profile fetching

Original behavior:

  • Fetch profile from main relay → 1 subscription created

New behavior:

  1. Fetch profile from main relay (subscription #1)
  2. If not found, try indexer relays
  3. If indexers fail, retry main relay (subscription #2)
  4. After 2 failures, mark profile as missing

Test fix:

test('should force refresh profile with forceRefresh parameter', () async {
  // Setup mock subscription manager
  when(
    mockSubscriptionManager.createSubscription(...),
  ).thenAnswer((_) async => 'sub_123');

  // Mock addRelay to return false (indexer relays not available)
  // This prevents MissingStubError and simulates unavailable indexers
  when(mockNostrService.addRelay(any)).thenAnswer((_) async => false);

  // ... test setup ...

  await service.fetchProfile(pubkey, forceRefresh: true);

  // Expect 2 calls: initial attempt + retry after indexer fallback
  verify(
    mockSubscriptionManager.createSubscription(...),
  ).called(2);
});

Notes

  • Don't just change the number: Always understand WHY the count changed
  • Mock fallback paths to fail gracefully: Return false/empty instead of throwing
  • Consider test isolation: Some tests may need different mock setups for different scenarios
  • Document behavior changes: Future maintainers need to understand the expected flow
  • This pattern applies universally: Java Mockito, Python unittest.mock, Jest, etc.

Related Patterns

  • When adding caching: methods may be called 0 times on cache hit
  • When adding circuit breakers: methods may be called fewer times on open circuit
  • When adding rate limiting: methods may be delayed or batched

References

レビュー

まだレビューはありません。使ってみた感想をお寄せください。

同じリポジトリのスキル

概要と使いどころ

Fix ArgoCD ExternalSecret deployment failing with "namespace X is not permitted in project Y". Use when: (1) ExternalSecret shows OutOfSync in ArgoCD but won't sync, (2) ArgoCD application status shows "namespace X is not permitted in project 'infrastructure'", (3) ExternalSecret targets a namespace managed by a different ArgoCD project, (4) Using apps-of-apps pattern with separate infrastructure and application projects.

日本語の概要は準備中です。原文の説明を表示しています。

divinevideo/divine-mobile2662026年10月13日 更新

Art direction for any content — reads text, PDF, Word, HTML, PPT, then proposes 2-3 creative directions with photography style, mood, and visual language. After selection, generates AI image prompts and visual briefs section-by-section. Use when the user shares content and needs visual direction, image sourcing, or creative direction for any material.

日本語の概要は準備中です。原文の説明を表示しています。

divinevideo/divine-mobile2662026年10月13日 更新

Fix "Null check operator used on a null value" errors when an object is set to null during an async await. Use when: (1) Object reference is nullified while awaiting, (2) Code accesses object with ! after await returns, (3) Cancel/dispose operations run concurrently with async operations on same object. Solution: capture local reference before await.

日本語の概要は準備中です。原文の説明を表示しています。

divinevideo/divine-mobile2662026年10月13日 更新

Add custom metadata headers (x-amz-meta-*) to AWS v4 signed requests for GCS S3-compatible API. Use when: (1) Adding custom metadata to GCS uploads via S3 API, (2) Getting signature mismatch errors after adding new headers, (3) x-amz-meta-* headers being ignored or causing 403 errors. Custom headers MUST be included in canonical headers and signed headers list.

日本語の概要は準備中です。原文の説明を表示しています。

divinevideo/divine-mobile2662026年10月13日 更新

Fix password/secret authentication failures caused by trailing newlines when creating Google Cloud secrets (or similar) with bash here-strings. Use when: (1) Password authentication fails with correct password, (2) Secret created with `<<< "value"` syntax, (3) Error like "password authentication failed" or "invalid token" despite correct value. Bash here-strings (`<<<`) add a trailing newline that corrupts secrets.

日本語の概要は準備中です。原文の説明を表示しています。

divinevideo/divine-mobile2662026年10月13日 更新

Fix silent video/media processing failures caused by URL extraction code that filters on file extensions (.mp4, .webm, .webp). Use when: (1) Media moderation, transcoding, or analysis silently skips files from Blossom or content-addressed storage servers, (2) URL extraction from Nostr event tags (imeta, r tags) drops URLs without recognized extensions, (3) CDN fallback URLs append .mp4 but the actual server uses extensionless content-addressed paths like /{sha256}. Common in Nostr video events (kind 34236) where different clients use different URL formats.

日本語の概要は準備中です。原文の説明を表示しています。

divinevideo/divine-mobile2662026年10月13日 更新

divinevideo のスキルをすべて見る

このスキルの問題を報告する