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.
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
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
@Constraintvalidators 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
- Add dependencies: Include
jakarta.validation-apiandhibernate-validatorin test scope - Create base test class: Build
Validatoronce in@BeforeEachusingValidation.buildDefaultValidatorFactory() - Test valid cases first: Verify objects pass without violations
- Test invalid cases: Assert constraint violations include correct property path and message
- Extract violation details: Use
getPropertyPath(),getMessage(),getInvalidValue() - Test custom validators: See
references/custom-validators.mdfor patterns - Use parameterized tests: Test multiple inputs efficiently with
@ParameterizedTest - 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
@Constraintannotations - 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
groupsparameter @ParameterizedTestwith@ValueSourceand@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
BaseValidationTestto 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
@NotNullfor mandatory fields combined with other constraints
Constraints and Warnings
- Null handling: Most constraints ignore null by default — combine
@NotNullwith other constraints for mandatory fields - Thread safety:
Validatorinstances are thread-safe and can be shared - Message localization: Test with different locales if i18n is required
- Cascading validation: Use
@Validon nested objects for recursive validation - Custom validators: Must be stateless and return
truefor 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
- Jakarta Bean Validation Spec
- how to use unit-test-bean-validation
How to use unit-test-bean-validation on Cursor
AI-first code editor with Composer
1Prerequisites
Before installing skills in Cursor, ensure your development environment meets these requirements:
- ›Cursor installed and configured on your development machine
- ›Node.js version 16.0+ with npm package manager (verify with
node --version) - ›Active project directory or workspace where you want to add unit-test-bean-validation
2Execute installation command
Execute the skills CLI command in your project's root directory to begin installation:
$npx skills add https://github.com/giuseppe-trisciuoglio/developer-kit --skill unit-test-bean-validationThe skills CLI fetches
unit-test-bean-validationfrom GitHub repositorygiuseppe-trisciuoglio/developer-kitand configures it for Cursor.3Select Cursor when prompted
The CLI will show a list of available agents. Use arrow keys to navigate and space to select Cursor:
◆ Which agents do you want to install to?││ ── Universal (.agents/skills) ── always included ────│ • Amp│ • Antigravity│ • Cline│ • Codex│ ●Cursor(selected)│ • Cursor│ • Windsurf4Verify installation
Confirm successful installation by checking the skill directory location:
.cursor/skills/unit-test-bean-validationReload or restart Cursor to activate unit-test-bean-validation. Access the skill through slash commands (e.g.,
/unit-test-bean-validation) or your agent's skill management interface.⚠Security & Verification Notice
We perform automated surface-level scans (Gen AI Scanner, Socket, Snyk) during installation. These checks detect common vulnerabilities but do not guarantee complete security. Always review skill source code and verify the publisher's reputation before production use.
Skills execute code in your development environment. Always verify the publisher's identity, review recent commits, and test in isolated environments before production deployment.
Additional Resources
GET_STARTED →List & Monetize Your Skill
Submit your Claude Code skill and start earning
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.Install skill using provided installation command
- 2.Test with simple use case relevant to your work
- 3.Evaluate output quality and relevance
- 4.Iterate on prompts to improve results
- 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▌
- 1Familiarize yourself with skill capabilities and limitations
- 2Start with low-risk, non-critical tasks
- 3Progress to more complex and valuable use cases
- 4Build expertise through regular use and experimentation
Discussion
Product Hunt–style comments (not star reviews)- No comments yet — start the thread.
general reviewsRatings
4.5★★★★★71 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