Testing Jakarta EE REST APIs with Mockito and JUnit 5

Here’s the revised version using @ExtendWith and @InjectMocks for CDI-style mocking:

Testing Jakarta EE REST APIs with Mockito and JUnit 5
Discover how to test Jakarta EE 10 APIs without a server using Mockito’s dependency injection and JUnit 5 extensions.

1. Maven Dependencies

Add these testing frameworks to your pom.xml:

2. REST Resource with CDI

A Jakarta EE resource using @Inject for service layer dependency:

3. Test Class with Mockito Injection

Using @ExtendWith and @InjectMocks to mock CDI dependencies:

Key Improvements

  1. No HTTP Server: Tests business logic directly without JerseyTest
  2. CDI-Style Mocking: @InjectMocks simulates Jakarta EE’s @Inject behavior
  3. Simplified Setup: Removes Jersey dependencies for pure unit testing

How It Works

  • @ExtendWith(MockitoExtension.class): Enables Mockito’s JUnit 5 integration
  • @Mock: Creates a mock instance of GreetingService
  • @InjectMocks: Injects mocks into fields annotated with @Inject
  • Direct Method Invocation: Tests resource methods without HTTP layer

Testing CDI Components

For full CDI container testing (including interceptors and producers), use CDI Test:

Common Issues & Fixes

Problem: NullPointerException in @InjectMocks
Solution: Ensure all dependencies are properly mocked with @Mock
Problem: CDI features missing
Solution: Use weld-junit5 for full CDI container testing
Problem: Annotation conflicts
Solution: Avoid mixing @InjectMocks with real CDI containers

When to Use This Approach
Unit Testing: Isolated service/resource testing
Fast Feedback: No server startup required
Mock Validation: Verify interactions with dependencies

Implementation Notes

  • Limited CDI Features: @InjectMocks only handles basic injection
  • No Interceptors: Use CDI Test or Arquillian for advanced scenarios
  • Jakarta EE 10: Requires Java 17+ and updated Mockito dependencies

Alternative for REST Endpoints
For HTTP layer testing with dependency injection:

Leave a Comment