Home > database >  Spring @WebFluxTest is loading @Component s
Spring @WebFluxTest is loading @Component s

Time:03-31

I am trying to create a @WebFluxTest in spring to test my controllers.

@WebFluxTest(value = {MyController.class})
public class MyControllerTest {

    @MockBean
    private MyService service;

    @Autowired
    private WebTestClient webTestClient;

    @Test
    void testSomething() {
         ...
    }

However, when I execute the test, I get a lot of: org.springframework.beans.factory.NoSuchBeanDefinitionException for dependencies of @Component s. Meaning that, Spring is trying to find dependencies of @Component when it should ignore those. I understand that if I use @WebFluxTest, spring should not scan the classpath for any @Component.

My Application class is only annotated with @SpringBootApplication.

What could I be missing here?

SOLUTION UPDATE:

So, I know what was happening. Actually, the class that I had annotated with @Component was an implementation of a WebFilter, and if I check the filter configured for a WebFluxTest (WebFluxTypeExcludeFilter) it adds WebFilter to the include part. That is why Spring was picking it up.

CodePudding user response:

The error that you're getting could be exactly due to the annotation @WebFluxTest not loading your @Component classes. Could it be that your MyService is instantiating any object that has @Component? Maybe your MyController

Exemplifying, supposing your MyService is like that:

@Service
@AllArgsConstructor
public class MyService {
    private final MyRepository repository;

    private final Env env;

    public void insert(...) {
        System.out.println(env.getApplicationName()   " random stuff");
        ...
    }
}

And your Env is annotated with @Component, you will get the same error (NoSuchBeanDefinitionException) if you try to use any method from the Env class since it's null due to @MockBean in MyControllerTest. The same goes for MyController if it's instantiating any @Component object

If that is the case, then in your MyControllerTest you could try adding @Import(Env.class) or even trying to use when() from mockito with a .thenReturn()

If all that doesn't work, could you please provide more info about your error log and service/controller classes?

CodePudding user response:

So, I know what was happening. Actually, the class that I had annotated with @Component was an implementation of a WebFilter, and if I check the filter configured for a WebFluxTest (WebFluxTypeExcludeFilter) it adds WebFilter to the include part. That is why Spring was picking it up.

  • Related