mercredi 2 décembre 2020

Spring dynamic @Bean registration with SpringApplicationBuilder failing in test

Trying to register beans dynamically via SpringApplicationBuilder class and it's working when running the app, but when trying to execute the test and trying to verify that the beans are defined in the context, they fail for the dynamic bean. Feel like I have to use another "magical" annotation for the tests for them to properly load the dynamic beans.

This is the code used and if you run the tests you will see that both cases will fail. BarService will fail also because FooService is registered dynamically via builder, but if you would remove the dependency it will pass the BarService test.

SpringApp.java

class FooService {

}

@Component
class BarService {
  private final FooService fooService;

  BarService(FooService fooService) {
    this.fooService = fooService;
  }
}


@SpringBootApplication
public class SpringApp {

  public static void main(String[] args) {
    new SpringApplicationBuilder()
      .sources(SpringApp.class)
      .initializers((ApplicationContextInitializer<GenericApplicationContext>) context -> {
        context.registerBean(FooService.class);
      })
      .run(args);
  }
}

SpringAppTest.java

@RunWith(SpringRunner.class)
@ContextConfiguration(classes = SpringApp.class)
public class SpringAppTest {
  @Autowired
  ApplicationContext context;

  @Test
  public void barService() {
    Assert.assertNotNull("The barService should not be null", context.getBean(BarService.class));
  }

  @Test
  public void contextLoads() {
    Assert.assertNotNull("The fooService should not be null", context.getBean(FooService.class));
  }
}

Aucun commentaire:

Enregistrer un commentaire