Home > front end >  Mock Bean for all JUnit Tests in Spring Boot
Mock Bean for all JUnit Tests in Spring Boot

Time:05-18

In Spring Boot, is there a way to mock a single bean for all existing JUnit tests, without changing the existing test classes (e.g., by adding an annotation or adding inheritance)? Like injecting a bean globally via configuration.

CodePudding user response:

Assuming you are using @SpringBootApplication in your main sources to define the Spring Boot application, you'll already have component scanning enabled for everything in that package (including nested packages).

When running tests, the classes (typically) in src/test/java are also added to the classpath, and are therefore available to be scanned as well.

For example, if you defined your @SpringBootApplication at com.example.boot.MySpringBootApplication, then com.example.boot.MyTestConfiguration would be eligible for component scanning, even though the former is in src/main and the latter in src/test. Putting it in the src/test/java directory would ensure that it only has an effect while running tests.

You can then define any "global" beans you would like in that configuration.

Using the package/class names I provided:

// File: src/test/java/com/example/boot/MyTestConfiguration.java

@Configuration // this will get component-scanned
public class MyTestConfiguration {

    @MockBean
    MyBean myGlobalMockBean;
}

Then, so long as you don't omit that Configuration from the Context Configuration, the MockBean should always be present under test.

  • Related