unit-test-bean-validation

giuseppe-trisciuoglio/developer-kit · updated Apr 8, 2026

MDX-style export adds YAML metadata + attribution linking explainx.ai and this canonical listing URL.

$npx skills add https://github.com/giuseppe-trisciuoglio/developer-kit --skill unit-test-bean-validation
0 commentsdiscussion
summary

Unit testing Jakarta Bean Validation constraints and custom validators without Spring context.

  • Covers testing built-in constraints ( @NotNull , @Email , @Min , @Max , @Size ) and custom @Constraint implementations with violation assertion patterns
  • Includes cross-field validation, validation groups for conditional rules, and parameterized test scenarios for multiple inputs
  • Provides setup patterns using Validation.buildDefaultValidatorFactory().getValidator() and assertion helpers to e
skill.md

Unit Testing Jakarta Bean Validation

Overview

This skill provides executable patterns for unit testing Jakarta Bean Validation annotations and custom validators using JUnit 5. Covers built-in constraints (@NotNull, @Email, @Min, @Max, @Size), custom @Constraint implementations, cross-field validation, and validation groups. Tests run in isolation without Spring context.

When to Use

  • Writing unit tests for Jakarta Bean Validation or JSR-380 constraints
  • Testing custom @Constraint validators and constraint violation messages
  • Testing bean validation logic in DTOs and request objects
  • Verifying cross-field validation (e.g., password matching)
  • Testing conditional validation with validation groups
  • Fast validation tests without Spring Boot context

Instructions

  1. Add dependencies: Include jakarta.validation-api and hibernate-validator in test scope
  2. Create base test class: Build Validator once in @BeforeEach using Validation.buildDefaultValidatorFactory()
  3. Test valid cases first: Verify objects pass without violations
  4. Test invalid cases: Assert constraint violations include correct property path and message
  5. Extract violation details: Use getPropertyPath(), getMessage(), getInvalidValue()
  6. Test custom validators: See references/custom-validators.md for patterns
  7. Use parameterized tests: Test multiple inputs efficiently with @ParameterizedTest
  8. Group validation tests: Use validation groups for conditional rules (see references/advanced-patterns.md)

Examples

Maven Setup

<dependency>
  <groupId>jakarta.validation</groupId>
  <artifactId>jakarta.validation-api</artifactId>
</dependency>
<dependency>
  <groupId>org.hibernate.validator</groupId>
  <artifactId>hibernate-validator</artifactId>
  <scope>test</scope>
</dependency>
<dependency>
  <groupId>org.assertj</groupId>
  <artifactId>assertj-core</artifactId>
  <scope>test</scope>
</dependency>

Common Test Setup

import jakarta.validation.*;
import jakarta.validation.ConstraintViolation;
import jakarta.validation.path.Path;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import static org.assertj.core.api.Assertions.*;

class BaseValidationTest {
  protected Validator validator;

  @BeforeEach
  void setUpValidator() {
    validator = Validation.buildDefaultValidatorFactory().getValidator();
  }
}

Testing Basic Constraints

class UserDtoTest extends BaseValidationTest {

  @Test
  void shouldPassValidationWithValidUser() {
    UserDto user = new UserDto("Alice", "[email protected]", 25);
    assertThat(validator.validate(user)).isEmpty();
  }

  @Test
  void shouldFailWhenNameIsNull() {
    UserDto user = new UserDto(null, "[email protected]", 25);
    assertThat(validator.validate(user))
      .extracting(ConstraintViolation::getMessage)
      .contains("must not be blank");
  }

  @Test
  void shouldFailWhenEmailIsInvalid() {
    UserDto user = new UserDto("Alice", "invalid-email", 25);
    Set<ConstraintViolation<UserDto>> violations = validator.validate(user);
    assertThat(violations)
      .extracting(ConstraintViolation::getPropertyPath)
      .extracting(Path::toString)
      .contains("email");
  }

  @Test
  void shouldFailWhenAgeIsBelowMinimum() {
    UserDto user = new UserDto("Alice", "[email protected]", -1);
    assertThat(validator.validate(user))
      .extracting(ConstraintViolation::getMessage)
      .contains("must be greater than or equal to 0");
  }

  @Test
  void shouldFailWhenMultipleConstraintsViolated() {
    UserDto user = new UserDto(null, "invalid", -5);
    assertThat(validator.validate(user)).hasSize(3);
  }
}

Testing Custom Validators

For custom constraint patterns, see references/custom-validators.md:

  • Creating @Constraint annotations
  • Implementing ConstraintValidator
  • Cross-field validation (password matching)
  • Stateless validator best practices

Testing Validation Groups

For validation groups and parameterized tests, see references/advanced-patterns.md:

  • Defining validation group interfaces
  • Conditional validation with groups parameter
  • @ParameterizedTest with @ValueSource and @CsvSource
  • Debugging failed validation tests

Best Practices

  • Test both valid and invalid: Every constraint needs both passing and failing test cases
  • Assert violation details: Verify property path, message, and constraint type
  • Test edge cases: null, empty string, whitespace-only, boundary values
  • Keep validators stateless: Custom validators must not maintain state
  • Use clear messages: Constraint messages should be user-friendly
  • Group related tests: Extend BaseValidationTest to share validator setup
  • Test error messages: Ensure messages match requirements

Common Pitfalls

  • Forgetting to test null values (most constraints ignore null by default)
  • Not verifying the property path in constraint violations
  • Testing validation at service/controller level instead of unit level
  • Creating overly complex custom validators
  • Missing @NotNull for mandatory fields combined with other constraints

Constraints and Warnings

  • Null handling: Most constraints ignore null by default — combine @NotNull with other constraints for mandatory fields
  • Thread safety: Validator instances are thread-safe and can be shared
  • Message localization: Test with different locales if i18n is required
  • Cascading validation: Use @Valid on nested objects for recursive validation
  • Custom validators: Must be stateless and return true for null values
  • Test isolation: Validation unit tests should not depend on Spring context or database

Troubleshooting

ValidatorFactory not found: Ensure jakarta.validation-api and hibernate-validator are on test classpath.

Custom validator not invoked: Verify @Constraint(validatedBy = YourValidator.class) annotation is correct.

Null values pass validation: This is expected behavior — constraints ignore null unless @NotNull is present.

Wrong violation count: Use hasSize() to verify exact count, check all fields in the object.

Property path incorrect: Ensure the field, not the getter, has the constraint annotation.

References

List & Monetize Your Skill

Submit your Claude Code skill and start earning

GET_STARTED →

Use Cases

Task Automation & Efficiency

Automate repetitive workflows and reduce manual effort

Example

Generate reports, summarize documents, draft communications

Save 3-5 hours per week on routine tasks

Knowledge Enhancement

Learn new skills, understand complex topics, get expert guidance

Example

Explain concepts, provide examples, suggest learning resources

Accelerate learning and skill development by 2x

Quality Improvement

Enhance output quality through reviews, suggestions, and refinements

Example

Review drafts, suggest improvements, catch errors

Improve work quality by 30-40% with less effort

Implementation Guide

Prerequisites

  • Claude Desktop or compatible AI client with skill support
  • Clear understanding of task or problem to solve
  • Willingness to iterate and refine outputs

Time Estimate

15-45 minutes depending on use case complexity

Installation Steps

  1. 1.Install skill using provided installation command
  2. 2.Test with simple use case relevant to your work
  3. 3.Evaluate output quality and relevance
  4. 4.Iterate on prompts to improve results
  5. 5.Integrate into regular workflow if valuable

Common Pitfalls

  • Expecting perfect results without iteration
  • Not providing enough context in prompts
  • Using skill for tasks outside its intended scope
  • Accepting outputs without review and validation

Best Practices

✓ Do

  • +Start with clear, specific prompts
  • +Provide relevant context and constraints
  • +Review and refine all outputs before using
  • +Iterate to improve output quality
  • +Document successful prompt patterns

✗ Don't

  • Don't use without understanding skill limitations
  • Don't skip validation of outputs
  • Don't share sensitive information in prompts
  • Don't expect skill to replace human judgment

💡 Pro Tips

  • Be specific about desired format and style
  • Ask for multiple options to choose from
  • Request explanations to understand reasoning
  • Combine AI efficiency with human expertise

When to Use This

✓ Use When

Use when skill capabilities match your task, clear ROI on time saved, and you can validate outputs. Best for repetitive tasks, learning, and quality improvement.

✗ Avoid When

Avoid when task requires deep expertise you can't validate, involves sensitive decisions, or when learning process is more valuable than speed of completion.

Learning Path

  1. 1Familiarize yourself with skill capabilities and limitations
  2. 2Start with low-risk, non-critical tasks
  3. 3Progress to more complex and valuable use cases
  4. 4Build expertise through regular use and experimentation

Discussion

Product Hunt–style comments (not star reviews)
  • No comments yet — start the thread.
general reviews

Ratings

4.571 reviews
  • Li Agarwal· Dec 20, 2024

    I recommend unit-test-bean-validation for anyone iterating fast on agent tooling; clear intent and a small, reviewable surface area.

  • Naina Srinivasan· Dec 16, 2024

    unit-test-bean-validation has been reliable in day-to-day use. Documentation quality is above average for community skills.

  • Sakshi Patil· Dec 12, 2024

    We added unit-test-bean-validation from the explainx registry; install was straightforward and the SKILL.md answered most questions upfront.

  • Kofi Harris· Dec 8, 2024

    Keeps context tight: unit-test-bean-validation is the kind of skill you can hand to a new teammate without a long onboarding doc.

  • Ira Gonzalez· Dec 4, 2024

    Registry listing for unit-test-bean-validation matched our evaluation — installs cleanly and behaves as described in the markdown.

  • Henry Yang· Nov 27, 2024

    unit-test-bean-validation is among the better-maintained entries we tried; worth keeping pinned for repeat workflows.

  • Ishan Anderson· Nov 23, 2024

    unit-test-bean-validation reduced setup friction for our internal harness; good balance of opinion and flexibility.

  • Meera Thompson· Nov 11, 2024

    Solid pick for teams standardizing on skills: unit-test-bean-validation is focused, and the summary matches what you get after install.

  • Pratham Ware· Nov 3, 2024

    Useful defaults in unit-test-bean-validation — fewer surprises than typical one-off scripts, and it plays nicely with `npx skills` flows.

  • Piyush G· Oct 22, 2024

    Registry listing for unit-test-bean-validation matched our evaluation — installs cleanly and behaves as described in the markdown.

showing 1-10 of 71

1 / 8