Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use @TestConfiguration

How to override @Configuation which is present under src/main/java with @TestConfiguration during unit tests?

@Configuration
public class AppConfig {
    

    @Bean
    public EmployeeService employeeService(){
        return new EmployeeService();
    }


}


@Component
public class ServerStartSetup implements CommandLineRunner {
    

    @Autowired
    private EmployeeService employeeService;

    public void run(String... args) {
        // do something with employee service
    }

}

I would like to override the above bean with some below custom bean for testing purposes.

@TestConfiguration
public class TestAppConfig {
    
    @Bean
    public EmployeeService employeeService(){
        return new FakeEmployeeService();
    }

}


@SpringBootTest
@Import(TestAppConfig.class)
public class UnitTest {
    



}

However AppConfig does not seem to be skipped. That is , it throws an error saying that there is a bean with same name employeeService. If I rename bean method name in the TestAppConfig, it injects the bean created via AppConfig.

How to fix this.?

Note: One possible solution is using @Profile. I am looking for anything other than using Profiles.

like image 435
KitKarson Avatar asked Oct 27 '25 14:10

KitKarson


1 Answers

I tested locally and found that changing the method name or @Bean to @Bean("fakeEmployeeService") and adding the @Primary annotation works.

@SpringBootTest
class DemoApplicationTests {

    @Autowired
    private EmployeeService employeeService;


    @TestConfiguration
    static class TestConfig {

        //@Bean("fakeEmployeeService")
        @Bean
        @Primary
        public EmployeeService employeeServiceTest() {
            return new EmployeeService() {
                @Override
                public void doSomething() {
                    System.out.println("Do something from test...");
                }
            };
        }
    }
    ...

}
like image 108
Kaz Avatar answered Oct 29 '25 04:10

Kaz



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!