name: test-development
description: Create comprehensive test suites by discovering and adapting to any testing framework, following project test patterns and ensuring robust coverage. Use when writing tests, improving coverage, validating functionality. Triggers: 'test', 'coverage', 'unit test', 'integration test', 'E2E', 'spec', '테스트', '커버리지', '단위 테스트', '통합 테스트', '테스트 작성', working with .test., .spec., test/, tests/.
allowed-tools:
- Read
- Write
- Edit
- Glob
- Grep
- Bash(test:*)
- Bash(go test:*)
- Bash(npm test:*)
- Bash(pytest:*)
- Bash(jest:*)
Test Development Methodology
This skill enables creation of comprehensive, project-appropriate tests by learning from existing test patterns and conventions.
Leverages: [codebase-analysis] skill for discovering testing frameworks and patterns.
Testing Philosophy
Pattern-Driven Testing
- Learn from existing tests: Match structure, naming, and assertions
- Framework agnostic: Adapt to any testing framework or methodology
- Project conventions: Follow discovered test organization
- Quality first: Robust coverage and validation
Test Coverage Principles
- Test what matters most for the project
- Follow project's testing pyramid (unit/integration/e2e ratio)
- Match existing coverage standards
- Ensure tests are maintainable and readable
Testing Workflow
Phase 1: Test Environment Discovery
Using [codebase-analysis]:
- Find tests: Locate all test files and directories
- Identify framework: Detect testing framework and runners
- Analyze structure: Learn test organization patterns
- Discover execution: Find test commands and scripts
- Understand coverage: Learn coverage tools and standards
Phase 2: Test Pattern Analysis
Study existing tests:
- Naming conventions: Test file and function naming
- Structure patterns: Setup/teardown, fixtures, helpers
- Assertion style: expect(), assert(), should(), etc.
- Test data: How fixtures and test data are managed
- Integration patterns: How tests interact with services
Phase 3: Test Implementation
Create tests matching patterns:
- Follow discovered test structure exactly
- Use same testing libraries and utilities
- Match naming and organization conventions
- Apply consistent assertion patterns
- Integrate with existing test data/fixtures
Framework Detection and Adaptation
JavaScript/TypeScript
describe('ProductService', () => {
let service: ProductService;
let mockRepository: jest.Mocked<ProductRepository>;
beforeEach(() => {
mockRepository = {
findById: jest.fn(),
save: jest.fn(),
} as any;
service = new ProductService(mockRepository);
});
it('should return product when found', async () => {
const productId = 1;
const expectedProduct = { id: productId, name: 'Test' };
mockRepository.findById.mockResolvedValue(expectedProduct);
const result = await service.getProduct(productId);
expect(result).toEqual(expectedProduct);
expect(mockRepository.findById).toHaveBeenCalledWith(productId);
});
});
Python
import pytest
from services.product_service import ProductService
class TestProductService:
@pytest.fixture
def service(self, mock_repository):
return ProductService(mock_repository)
@pytest.fixture
def mock_repository(self, mocker):
return mocker.Mock()
def test_get_product_returns_product_when_found(self, service, mock_repository):
product_id = 1
expected_product = Product(id=product_id, name="Test")
mock_repository.find_by_id.return_value = expected_product
result = service.get_product(product_id)
assert result == expected_product
mock_repository.find_by_id.assert_called_once_with(product_id)
Go
package product
import (
"testing"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/mock"
)
type MockRepository struct {
mock.Mock
}
func (m *MockRepository) FindByID(id int) (*Product, error) {
args := m.Called(id)
return args.Get(0).(*Product), args.Error(1)
}
func TestProductService_GetProduct_ReturnsProductWhenFound(t *testing.T) {
mockRepo := new(MockRepository)
service := NewProductService(mockRepo)
productID := 1
expectedProduct := &Product{ID: productID, Name: "Test"}
mockRepo.On("FindByID", productID).Return(expectedProduct, nil)
result, err := service.GetProduct(productID)
assert.NoError(t, err)
assert.Equal(t, expectedProduct, result)
mockRepo.AssertExpectations(t)
}
Java
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.DisplayName;
import org.mockito.Mock;
import org.mockito.InjectMocks;
import org.mockito.junit.jupiter.MockitoExtension;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Mockito.*;
@ExtendWith(MockitoExtension.class)
class ProductServiceTest {
@Mock
private ProductRepository productRepository;
@InjectMocks
private ProductService productService;
@Test
@DisplayName("Should return product when found")
void getProduct_WhenProductExists_ReturnsProduct() {
Long productId = 1L;
Product expectedProduct = Product.builder()
.id(productId)
.name("Test Product")
.build();
when(productRepository.findById(productId))
.thenReturn(Optional.of(expectedProduct));
Product result = productService.getProduct(productId);
assertThat(result).isEqualTo(expectedProduct);
verify(productRepository).findById(productId);
}
}
Test Pattern Matching
Test Naming Conventions
def test_createProduct_withValidData_returnsProduct():
pass
def test_createProduct_withDuplicateName_raisesValidationError():
pass
def test_createProduct_withNegativePrice_raisesValidationError():
pass
Test Organization
describe('OrderService', () => {
describe('createOrder', () => {
it('should create order with valid data', () => {});
it('should throw error with invalid customer', () => {});
it('should throw error with empty items', () => {});
});
describe('cancelOrder', () => {
it('should cancel order when pending', () => {});
it('should throw error when already shipped', () => {});
});
});
Assertion Style Matching
expect(result).toBe(expected);
expect(array).toHaveLength(3);
expect(object).toEqual({ id: 1, name: 'Test' });
expect(fn).toHaveBeenCalledWith(arg1, arg2);
assert.equal(result, expected);
Test Data Management
@pytest.fixture
def valid_product_data():
return {
"name": "Test Product",
"price": 99.99,
"category": "Electronics"
}
def test_create_product_success(valid_product_data):
product = create_product(valid_product_data)
assert product.name == valid_product_data["name"]
Coverage Strategies
Unit Testing
@Test
void calculateDiscount_RegularCustomer_Returns10Percent() {
}
@Test
void calculateDiscount_NullCustomer_ThrowsException() {
}
@Test
void calculateDiscount_ZeroAmount_ReturnsZero() {
}
Integration Testing
describe('OrderController Integration', () => {
let app: INestApplication;
let orderRepository: Repository<Order>;
beforeAll(async () => {
const module = await Test.createTestingModule({
imports: [AppModule],
}).compile();
app = module.createNestApplication();
await app.init();
});
it('should create order end-to-end', async () => {
const response = await request(app.getHttpServer())
.post('/orders')
.send({ customerId: 1, items: [...] })
.expect(201);
expect(response.body).toHaveProperty('id');
});
});
End-to-End Testing
def test_user_can_complete_purchase_flow(browser):
browser.goto("/products/1")
browser.click("#add-to-cart")
browser.click("#checkout")
browser.fill("#shipping-address", "123 Main St")
browser.click("#complete-order")
assert browser.is_visible("#order-confirmation")
Test Quality Standards
AAA Pattern (Arrange-Act-Assert)
func TestOrderService_ProcessOrder(t *testing.T) {
order := &Order{
ID: 1,
CustomerID: 100,
Items: []Item{{ProductID: 1, Quantity: 2}},
}
mockRepo := new(MockRepository)
service := NewOrderService(mockRepo)
result, err := service.ProcessOrder(order)
assert.NoError(t, err)
assert.Equal(t, OrderStatus.Processing, result.Status)
}
Test Independence
class TestUserService:
def test_create_user(self):
service = UserService()
user = service.create_user({"email": "test@example.com"})
assert user.email == "test@example.com"
def test_delete_user(self):
service = UserService()
pass
Clear Test Failures
it('should calculate correct total with tax', () => {
const result = calculator.calculateTotal(100);
expect(result.subtotal).toBe(100);
expect(result.tax).toBe(10);
expect(result.total).toBe(110);
});
Test Execution Integration
Match Project Test Commands
"scripts": {
"test": "jest",
"test:watch": "jest --watch",
"test:coverage": "jest --coverage"
}
npm test
npm run test:coverage
CI/CD Integration
Quality Checklist
Before finalizing tests:
Anti-Patterns to Avoid
❌ Testing Implementation Details:
expect(service.internalCache.size).toBe(3);
expect(service.getUsers()).toHaveLength(3);
❌ Fragile Tests:
assert user.created_at == datetime(2024, 1, 1, 12, 30, 45)
assert user.created_at is not None
assert user.created_at <= datetime.now()
❌ Dependent Tests:
@Test
void test1_createUser() { ... }
@Test
void test2_updateUser() {
}
Remember: Great tests are readable, maintainable, and follow project patterns. Use [codebase-analysis] to discover testing conventions, then create tests that feel native to the project's testing culture.