xiaohongshu
xiaohongshu
brokle-testing
Use this skill when writing, reviewing, or improving tests for the Brokle platform. This includes creating service tests, domain tests, integration tests, or understanding what to test versus what to skip based on the pragmatic testing philosophy.
Full skill instructions
Expert guidance for writing pragmatic, high-value tests following Brokle's testing philosophy.
Core Principle: Test Business Logic, Not Framework Behavior
Target Metrics:
Acceptable Ratios:
// ============================================================================
// Mock Repositories (Full Interface Implementation)
// ============================================================================
type MockUserRepository struct {
mock.Mock
}
func (m *MockUserRepository) Create(ctx context.Context, user *authDomain.User) error {
args := m.Called(ctx, user)
return args.Error(0)
}
func (m *MockUserRepository) GetByID(ctx context.Context, id ulid.ULID) (*authDomain.User, error) {
args := m.Called(ctx, id)
if args.Get(0) == nil {
return nil, args.Error(1)
}
return args.Get(0).(*authDomain.User), args.Error(1)
}
// Implement ALL interface methods (even if not used in test)
// ============================================================================
// HIGH-VALUE TESTS: Complex Business Logic
// ============================================================================
func TestUserService_CreateUser(t *testing.T) {
tests := []struct {
name string
input *CreateUserRequest
mockSetup func(*MockUserRepository)
expectedErr error
checkResult func(*testing.T, *CreateUserResponse)
}{
{
name: "success - valid user",
input: &CreateUserRequest{
Email: "[email protected]",
Name: "Test User",
},
mockSetup: func(repo *MockUserRepository) {
// Expect email check (not found)
repo.On("GetByEmail", mock.Anything, "[email protected]").
Return(nil, authDomain.ErrNotFound)
// Expect user creation
repo.On("Create", mock.Anything, mock.MatchedBy(func(user *authDomain.User) bool {
return user.Email == "[email protected]" && user.Name == "Test User"
})).Return(nil)
},
expectedErr: nil,
checkResult: func(t *testing.T, resp *CreateUserResponse) {
assert.NotNil(t, resp)
assert.NotEqual(t, ulid.ULID{}, resp.User.ID)
assert.Equal(t, "[email protected]", resp.User.Email)
},
},
{
name: "error - user already exists",
input: &CreateUserRequest{
Email: "[email protected]",
Name: "Existing User",
},
mockSetup: func(repo *MockUserRepository) {
// Return existing user
existingUser := &authDomain.User{
ID: ulid.New(),
Email: "[email protected]",
}
repo.On("GetByEmail", mock.Anything, "[email protected]").
Return(existingUser, nil)
// No create call expected
},
expectedErr: errors.New("conflict"), // Check error message, not sentinel
checkResult: nil,
},
{
name: "error - repository failure",
input: &CreateUserRequest{
Email: "[email protected]",
Name: "Test User",
},
mockSetup: func(repo *MockUserRepository) {
repo.On("GetByEmail", mock.Anything, "[email protected]").
Return(nil, authDomain.ErrNotFound)
repo.On("Create", mock.Anything, mock.Anything).
Return(fmt.Errorf("database error"))
},
expectedErr: errors.New("internal"), // Check error message, not sentinel
checkResult: nil,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
// Setup mocks
mockRepo := new(MockUserRepository)
tt.mockSetup(mockRepo)
// Create service
service := NewUserService(mockRepo)
// Execute
result, err := service.CreateUser(context.Background(), tt.input)
// Assert errors
if tt.expectedErr != nil {
assert.Error(t, err)
assert.ErrorIs(t, err, tt.expectedErr)
} else {
assert.NoError(t, err)
}
// Assert results
if tt.checkResult != nil {
tt.checkResult(t, result)
}
// Verify all mock expectations were met
mockRepo.AssertExpectations(t)
})
}
}
tests := []struct {
name string
input InputType
mockSetup func(*MockRepo)
expectedErr error
checkResult func(*testing.T, *Result)
}{
{
name: "success case",
input: validInput,
mockSetup: func(repo *MockRepo) {
repo.On("Method", mock.Anything, mock.Anything).Return(nil)
},
expectedErr: nil,
checkResult: func(t *testing.T, result *Result) {
assert.NotNil(t, result)
},
},
}
type MockUserRepository struct {
mock.Mock
}
// Implement ALL methods from interface
func (m *MockUserRepository) Create(ctx context.Context, user *User) error {
args := m.Called(ctx, user)
return args.Error(0)
}
func (m *MockUserRepository) GetByID(ctx context.Context, id ulid.ULID) (*User, error) {
args := m.Called(ctx, id)
if args.Get(0) == nil {
return nil, args.Error(1)
}
return args.Get(0).(*User), args.Error(1)
}
// Implement all other methods even if unused
mockSetup: func(userRepo *MockUserRepo, orgRepo *MockOrgRepo) {
// Use mock.MatchedBy for complex validation
userRepo.On("Create", mock.Anything, mock.MatchedBy(func(user *User) bool {
return user.Email != "" && user.Name != ""
})).Return(nil)
// Multiple expectations in order
orgRepo.On("GetByID", mock.Anything, orgID).Return(org, nil)
orgRepo.On("Update", mock.Anything, mock.Anything).Return(nil)
}
checkResult: func(t *testing.T, result *CreateUserResponse) {
assert.NotNil(t, result)
assert.NotEqual(t, ulid.ULID{}, result.User.ID)
assert.Equal(t, "[email protected]", result.User.Email)
assert.NotNil(t, result.User.CreatedAt)
assert.Equal(t, "active", result.User.Status)
}
// ALWAYS call AssertExpectations on all mocks
mockUserRepo.AssertExpectations(t)
mockOrgRepo.AssertExpectations(t)
mockPublisher.AssertExpectations(t)
Only test complex business logic:
// ✅ HIGH-VALUE: Business logic calculation
func TestSpan_CalculateLatency(t *testing.T) {
startTime := time.Now()
endTime := startTime.Add(150 * time.Millisecond)
tests := []struct {
name string
span *Span
expected *int
}{
{
name: "with valid end time",
span: &Span{
StartTime: startTime,
EndTime: &endTime,
},
expected: func() *int { val := 150; return &val }(),
},
{
name: "without end time",
span: &Span{
StartTime: startTime,
EndTime: nil,
},
expected: nil,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
result := tt.obs.CalculateLatency()
if tt.expected == nil {
assert.Nil(t, result)
} else {
assert.NotNil(t, result)
assert.Equal(t, *tt.expected, *result)
}
})
}
}
func TestUserService_Integration(t *testing.T) {
// Skip if not running integration tests
if testing.Short() {
t.Skip("Skipping integration test")
}
// Setup test database
db := setupTestDB(t)
defer cleanupTestDB(t, db)
// Setup real dependencies
userRepo := repository.NewUserRepository(db)
service := services.NewUserService(userRepo)
// Test complete workflow
user := &CreateUserRequest{
Email: "[email protected]",
Name: "Integration Test",
}
result, err := service.CreateUser(context.Background(), user)
require.NoError(t, err)
require.NotEqual(t, ulid.ULID{}, result.User.ID)
// Verify persistence
retrieved, err := service.GetUser(context.Background(), result.User.ID)
require.NoError(t, err)
assert.Equal(t, result.User.Email, retrieved.User.Email)
}
# All tests
make test
# Unit tests only (skip integration)
make test-unit
# Integration tests with real databases
make test-integration
# With coverage
make test-coverage
# Specific package
go test ./internal/core/services/observability -v
# Specific test
go test ./internal/core/services/observability -run TestUserService_Create -v
# With race detection
go test -race ./...
# Skip integration tests
go test -short ./...
Before Writing Tests:
internal/core/services/observability/*_test.goTest Implementation:
AssertExpectations(t)What NOT to Test:
docs/TESTING.md - Complete testing guideinternal/core/services/observability/*_test.go - Reference implementationsprompts/testing.txt - AI-assisted test generationxiaohongshu
technical spec
product ux expert
database patterns
Conduct multi-agent task orchestration and workflow coordination.
Initialize project with Conductor artifacts (product definition,
Expert in web animations, transitions, and motion design using Framer Motion and CSS
Creates Mermaid and ASCII diagrams for flowcharts, architecture, ERDs, state machines, mindmaps, and more. Use when user mentions diagram, flowchart, mermaid, ASCII diagram, text diagram, terminal diagram, visualize, C4, mindmap, architecture diagram, sequence diagram, ERD, or needs visual docume...
PostgreSQL bindings for H3 hexagonal grid system. Use when working with H3 cells in Postgres, including spatial indexing, geometry/geography integration, and raster analysis.
Context-Driven Development skill for projects using Conductor. Use this skill when you detect a `conductor/` directory in the project, when working on tasks defined in a `plan.md` file, or when the user asks about tracks, specs, or plans. Automatically applies TDD workflow, tracks task completion...
Display project status, active tracks, and next actions
Official Stakpak application containerization standard operating procedure, a step-by-step guidline to properly dockerize applications. This is a rule book curated by the Stakpak Team.
Generate, edit, and beat-sync AI video with leading models in one workspace.
The world's fastest calendar for remote work
Transform Your Design with AI Designer by ImgCreator.ai
Revolutionizing Video Production with AI-Powered Creativity
Extend an image past the frame and let AI fill the new aspect ratio.
Discover your celebrity doppelgänger with StarByFace!
ChainClarity explains 700+ crypto whitepapers in plain English, with layered summaries, comparisons, research tools, alerts, and a $4.99 Pro plan.
Opus.ai: Revolutionize Your Web Experience