Is the usage of lombok's @RequiredArgsConstructor good or bad in @QuarkusTest integration tests? #52560
Replies: 3 comments
|
Great question! The short answer: avoid Why it's problematicQuarkus uses CDI (Contexts and Dependency Injection) under the hood. CDI has specific rules about how beans are instantiated:
Best practice@QuarkusTest
class MyServiceTest {
@Inject
MyService myService; // ✅ Standard Quarkus way
@InjectMock
ExternalClient client; // ✅ For mocks
@Test
void shouldDoSomething() {
// test code
}
}In production code (non-test)For application beans, constructor injection IS recommended, but use @ApplicationScoped
public class MyService {
private final MyRepository repo;
@Inject // explicit — no Lombok needed
public MyService(MyRepository repo) {
this.repo = repo;
}
}Or if you really want Lombok, combine it with @ApplicationScoped
@RequiredArgsConstructor(onConstructor_ = @Inject)
public class MyService {
private final MyRepository repo;
}But note that Quarkus (unlike Spring) does not auto-detect single-constructor injection — you always need TL;DR: Use |
|
To add a bit more nuance to the existing answer: Why it silently failsQuarkus test classes annotated with
Lombok's The one case where it "works" (and shouldn't be relied on)If your test class has no The correct pattern in
|
|
Both existing answers explain why it breaks — to complete the picture, here is how to actually fix it when you want constructor injection in Use @QuarkusTest
public class MyServiceTest {
private final MyService myService;
@Inject
public MyServiceTest(MyService myService) {
this.myService = myService;
}
}Or switch to field injection for test classes: @QuarkusTest
public class MyServiceTest {
@Inject
MyService myService; // field injection works perfectly with CDI
}If you need |
Uh oh!
There was an error while loading. Please reload this page.
I wonder if there is a reason that @requiredargsconstructor should be avoided or not. What is best practice and why?
All reactions