#StackBounty: #java #spring #spring-boot #spring-mvc How do I unit-test the controller of a Spring Boot application with a DataSource d…

Bounty: 50

Consider the following basic Spring Boot application:

@SpringBootApplication
@ComponentScan(basePackages = "webmvctestproblem.foo")
public class Application {
  public static void main(String[] args) {
    run(Application.class, args);
  }
}

It contains only two other beans. One controller:

@RestController
class Greeter {
  @GetMapping("/")
  String greet() {
    return "Hello, world!";
  }
}

And one configuration in webmvctestproblem.foo containing a DataSource dependency:

@Configuration
class Bar {
  @Autowired
  private DataSource dataSource;
}

Running the application normally (through gradlew bootrun, e.g.) succeeds. Thus, confirming that the app is configured correctly under normal conditions.

However, running the following test causes a runtime error because Spring still attempts to resolve the data source bean dependency on the configuration class:

@RunWith(SpringRunner.class)
@WebMvcTest
public class GreeterTest {
  @Test
  public void test() throws Exception {
  }
}

Of course, there isn’t one to resolve because the test is a @WebMvcTest that is designed to create only MVC-related beans.

How do I get rid of the error? I have already tried excluding the configuration class using the excludeFilters attribute of the existing @WebMvcTest annotation and a new @ComponentScan annotation on the test itself. I don’t want to resort to turning it into an integration test with @SpringBootTest.

(The project is also available on GitHub for convenience.)


Get this bounty!!!

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.