@Component not being read in Spring test

Viewed 48

I created an Integration test to test the new feature I just added but the Spring wiring is not working. The unit tests all work and the existing Spring integration tests still work but I am unable to Autowire my new class

Here is the error message –

org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'com.xxx.xxx.etc.MyNewClassTest’: Unsatisfied dependency expressed through field 'sut'; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'com.xxx.xxx.etc.MyNewClass ' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}

The new class –

@Slf4j
@Component
public class MyNewClass extends AbstractRetryJob<Event> {

My test -

@ExtendWith(SpringExtension.class)
class MyNewClassTest {
  @Autowired private MyNewClass sut;

Any idea on what is going wrong?

1 Answers

Adding @ExtendWith(SpringExtension.class) is not enough to create the Spring context. You need to add @SpringBootTest to your MyNewClassTest. Per the appropriate comment, you can drop @ExtendWith(SpringExtension.class)

@SpringBootTest
class MyNewClassTest {

  @Autowired private MyNewClass sut;
}
Related