본문으로 건너뛰기
cccskills
무료GitHub에 공개

mocking-test-generator

Generate unit tests with proper mocking for Python (unittest.mock/pytest) or Java (Mockito/JUnit) code. Use when users request test generation, unit tests with mocks, or testing code that has external dependencies like database calls, API requests, file I/O, or network operations. Automatically identifies dependencies to mock and creates executable, maintainable test code.

한국어 요약은 준비 중입니다. 원문 설명을 표시하고 있습니다.

설치 방법 보기

포함된 파일(3)

  • SKILL.md6.1 KB
  • references/java_patterns.md6.2 KB
  • references/python_patterns.md3.1 KB

SKILL.md(원문)

설치하기 전에 에이전트에게 전달되는 지시 내용을 확인할 수 있습니다.

Mocking Test Generator

Generate unit tests with proper mocking of external dependencies for Python and Java code.

Workflow

  1. Analyze the code - Identify external dependencies, side effects, and testable units
  2. Select framework - Determine Python (unittest.mock/pytest) or Java (Mockito/JUnit)
  3. Generate mocks - Create mock objects for external dependencies
  4. Write tests - Generate executable test code with assertions
  5. Add documentation - Include clear comments explaining mocks and test logic

Step 1: Analyze the Code

Read the target code to identify:

  • External dependencies: API clients, database connections, third-party libraries
  • I/O operations: File reads/writes, network requests, system calls
  • Side effects: Email sending, logging, state modifications
  • Testable units: Functions, methods, or classes to test in isolation

Ask clarifying questions if:

  • Multiple functions/classes exist (which to test?)
  • Testing scope is unclear (unit vs integration?)
  • Mock behavior needs specification (return values, exceptions?)

Step 2: Select Framework

Python: Use unittest.mock with pytest or unittest

  • Prefer @patch decorator for external calls
  • Use Mock() objects for complex dependencies
  • Apply pytest.fixture for reusable mocks

Java: Use Mockito with JUnit 5

  • Use @Mock annotation for dependencies
  • Apply @ExtendWith(MockitoExtension.class) to test class
  • Use when().thenReturn() for stubbing

Step 3: Generate Mocks

Identify what to mock:

Always mock:

  • External API calls (HTTP requests, REST clients)
  • Database connections and queries
  • File system operations
  • Network I/O
  • Time/date functions
  • Random number generators
  • Environment variables

Never mock (unless explicitly requested):

  • Internal business logic
  • Pure functions
  • Data structures
  • Simple utilities

For common patterns, reference:

Step 4: Write Tests

Generate test code that:

  1. Imports - Include necessary testing and mocking libraries
  2. Setup - Initialize mocks and test fixtures
  3. Execution - Call the function/method under test
  4. Assertions - Verify expected behavior and outputs
  5. Verification - Confirm mocks were called correctly

Test structure:

# Python example
from unittest.mock import patch, Mock
import pytest

@patch('module.external_dependency')
def test_function_name(mock_dependency):
    # Arrange: Setup mock behavior
    mock_dependency.return_value = expected_value

    # Act: Execute function under test
    result = function_under_test(input_data)

    # Assert: Verify results
    assert result == expected_output
    mock_dependency.assert_called_once_with(expected_args)
// Java example
@ExtendWith(MockitoExtension.class)
class ServiceTest {
    @Mock
    private ExternalDependency dependency;

    @Test
    void testMethodName() {
        // Arrange: Setup mock behavior
        when(dependency.method()).thenReturn(expectedValue);

        // Act: Execute method under test
        Service service = new Service(dependency);
        String result = service.methodUnderTest();

        // Assert: Verify results
        assertEquals(expectedOutput, result);
        verify(dependency).method();
    }
}

Include:

  • Multiple test cases for different scenarios (happy path, edge cases, errors)
  • Descriptive test names that explain what is being tested
  • Setup/teardown if needed for test isolation

Step 5: Add Documentation

Include comments that explain:

  • What external dependency is being mocked and why
  • What behavior the mock simulates
  • What the test verifies

Keep comments concise and focused on non-obvious aspects.

Output Format

Provide:

  1. Complete test file - Fully executable with all imports
  2. Test class/module - Properly structured for the framework
  3. Multiple test methods - Cover main scenarios
  4. Clear naming - Descriptive test and variable names

Do not:

  • Modify the original code under test
  • Mock internal logic unless explicitly requested
  • Generate incomplete or pseudo-code tests

Example Usage

User request: "Generate unit tests for this Python function that calls an external API"

Response:

  1. Read the function code
  2. Identify the API call to mock
  3. Generate pytest test file with @patch decorator
  4. Include tests for success case, error handling, and edge cases
  5. Add comments explaining the mock setup

Framework-Specific Notes

Python (pytest):

  • Use @pytest.fixture for reusable mock setups
  • Apply @patch as decorator or context manager
  • Use mock_open for file operations
  • Apply @patch.dict for environment variables

Python (unittest):

  • Use unittest.TestCase base class
  • Apply @patch decorator or patch() context manager
  • Use setUp() and tearDown() methods
  • Call self.assert* methods

Java (Mockito + JUnit 5):

  • Use @ExtendWith(MockitoExtension.class) on test class
  • Apply @Mock for dependencies
  • Use @BeforeEach for setup, @AfterEach for teardown
  • Apply ArgumentCaptor to verify complex arguments
  • Use MockedStatic for static method mocking (Mockito 3.4+)

Common Patterns

Reference files contain detailed examples for:

Python (references/python_patterns.md):

  • External API calls
  • Database operations
  • File system operations
  • Environment variables
  • Time-dependent code
  • Exception handling

Java (references/java_patterns.md):

  • External API calls
  • Database operations
  • File system operations
  • Void methods
  • Exception handling
  • Argument captors
  • Static method mocking
  • Constructor mocking

리뷰

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

댓글

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

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

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

0 / 1,000자

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

같은 저장소의 스킬

Applies abstract interpretation using different abstract domains (intervals, octagons, polyhedra, sign, congruence) to statically analyze program variables and infer invariants, value ranges, and relationships. Use when analyzing program properties, inferring loop invariants, detecting potential errors, or understanding variable relationships through static analysis.

한국어 요약은 준비 중입니다. 원문 설명을 표시하고 있습니다.

ArabelaTso/Skills-4-SE2562026년 8월 21일 업데이트

Uses abstract interpretation to automatically infer loop invariants, function preconditions, and postconditions for formal verification. Generates invariants that capture program behavior and support correctness proofs in Dafny, Isabelle, Coq, and other verification systems. Use when adding formal specifications to code, generating verification conditions, inferring contracts for functions, or discovering loop invariants for proofs.

한국어 요약은 준비 중입니다. 원문 설명을 표시하고 있습니다.

ArabelaTso/Skills-4-SE2562026년 8월 21일 업데이트

Performs abstract interpretation over source code to infer possible program states, variable ranges, and data properties without executing the program. Reports potential runtime errors including out-of-bounds accesses, null dereferences, type inconsistencies, division by zero, and integer overflows. Use when analyzing code for potential runtime errors, performing static analysis, checking safety properties, or verifying program behavior without execution.

한국어 요약은 준비 중입니다. 원문 설명을 표시하고 있습니다.

ArabelaTso/Skills-4-SE2562026년 8월 21일 업데이트

Performs abstract interpretation to produce summarized execution traces and high-level program behavior representations. Highlights key control flow paths, variable relationships, loop invariants, function summaries, and potential runtime states using abstract domains (intervals, signs, nullness, etc.). Use when analyzing program behavior, understanding execution paths, computing loop invariants, tracking variable ranges, detecting potential runtime errors, or generating program summaries without concrete execution.

한국어 요약은 준비 중입니다. 원문 설명을 표시하고 있습니다.

ArabelaTso/Skills-4-SE2562026년 8월 21일 업데이트

Create ACSL (ANSI/ISO C Specification Language) formal annotations for C/C++ programs. Use this skill when working with formal verification, adding function contracts (requires/ensures), loop invariants, assertions, memory safety annotations, or any ACSL specifications. Supports Frama-C verification and generates comprehensive formal specifications for C/C++ code.

한국어 요약은 준비 중입니다. 원문 설명을 표시하고 있습니다.

ArabelaTso/Skills-4-SE2562026년 8월 21일 업데이트

CLI-based browser automation with persistent page state using ref-based element interaction. Use when users ask to navigate websites, interact with web pages, fill forms, take screenshots, test web applications, or extract information from web pages.

한국어 요약은 준비 중입니다. 원문 설명을 표시하고 있습니다.

ArabelaTso/Skills-4-SE2562026년 8월 21일 업데이트

ArabelaTso의 스킬 모두 보기

이 스킬의 문제 신고