본문으로 건너뛰기
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

리뷰

아직 리뷰가 없습니다. 사용해 본 소감을 남겨 주세요.

댓글

로그인 없이 쓸 수 있습니다. 사용 후기, 질문, 작동하지 않은 환경 등을 편하게 남겨 주세요.

아직 댓글이 없습니다. 첫 댓글을 남겨 보세요.

보내면 바로 공개됩니다. 이메일 주소나 전화번호 같은 개인 정보는 쓰지 마세요. URL은 2개까지입니다.

0 / 1,000자

이 양식은 reCAPTCHA로 보호되며 Google 개인정보처리방침 및 서비스 약관이 적용됩니다.

같은 저장소의 스킬

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월 19일 업데이트

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월 19일 업데이트

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월 19일 업데이트

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월 19일 업데이트

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월 19일 업데이트

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월 19일 업데이트

divinevideo의 스킬 모두 보기

이 스킬의 문제 신고