Search code examples
javaspring-bootunit-testingjunitspring-webflux

Test case for my controller in the spring boot reactive web application gives errors


package com.example.demo4.controller;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.reactive.WebFluxTest;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.web.reactive.server.WebTestClient;

@RunWith(SpringRunner.class)
@WebFluxTest(UserController.class)  // Specify the controller class to test
public class UserControllerTest {

@Autowired
private WebTestClient webTestClient;

@Test
public void getAllUsers() {
    webTestClient.get().uri("/api/users").exchange()
            .expectStatus().isOk();
}

}

this is my user controller test. I cant find what is the issue here?

09:48:11.650 [main] INFO org.springframework.test.context.support.AnnotationConfigContextLoaderUtils -- Could not detect default configuration classes for test class [com.example.demo2.controller.UserControllerTest]: UserControllerTest does not declare any static, non-private, non-final, nested classes annotated with @Configuration.

it gives this error

I want to run the test case without any error.


Solution

  • There is a common practice in Spring Tests especially while doing testing using annotations like @WebFluxTest or @DataJpaTest to feed your test classes with an empty configuration so that you can run your tests without any errors. So you need to create a Configuration class and mark it with @Configuration annotation and you can keep it blank

    @Configuration
    public class SampleConfig{
      // You can keep it blank
    }
    

    After creating this configuration class you need to @Include this to your Test class so that requirements can be satisfied

    @RunWith(SpringRunner.class)
    @WebFluxTest(UserController.class)
    @Import(TestConfig.class)
    public class UserControllerTest {
      // Rest of your code
    }