2

I've got a CDI web application which has a ServletContextListener to initialise a few things on startup.

In that ServletContextListener, this (among other things) happens:

@Inject
Config config;

public void contextInitialized(ServletContextEvent event) {
    ....

    config.init(....)
}

This works well enough, as this makes sure that the init is performed before other CDI beans are instantiated (such as App, which injects Config itself too)

However, I'm unable to work out how to realise this logic for unit testing. With CDI-Unit from jglue, I can do this in my test class:

@Inject
Config config;

@Inject
App application;

But when I run my test, I keep on getting issues, as the @PostConstruct in App needs Config to be inited already. So, how can I possibly call the Config.init() method in time?

Steven De Groote
  • 2,187
  • 5
  • 32
  • 52
  • Have you tried using `Instance`? E.g. programmatic lookup. It won't be resolved to an actual bean unless you do `Instance.select(...).get()`. This might delay it enough for you to call `Config` first and `App` later on. Lemme know if that works. – Siliarus Sep 20 '17 at 06:49
  • Wandering off a bit, but is the system that I describe of our application so strange then? I'm ok with changing it to something more "standard" perhaps, but thought it was reasonably straightforward. – Steven De Groote Sep 20 '17 at 07:42
  • In fact, have a not-self-contained bean, which needs to be initialized via an external call in the system, *is* unusual. – mtj Sep 20 '17 at 11:21
  • OK. And what would be the better solution then? – Steven De Groote Sep 20 '17 at 14:00
  • That depends very much on what your init-method does. Probably, you could switch to a producer method which creates the completely initialized config object. I *think* it should even be possible to inject the servlet context there (not 100% sure though). Or have the constructor of config init the complete object (here, constructor-injection of the servlet context should be possible, too). However you do it, each bean should be completely initialized at the time it is available for injection. This way, the container can manage all dependencies by itself. – mtj Sep 21 '17 at 05:57

0 Answers0