2

I have some beans that query the database in a @PostConstruct method. Thus, I need the database to be ready before autowiring occurs. Is this possible?

This is my test class:

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = { "classpath:spring/app.xml",
        "classpath:spring/test-beans-context.xml" })
@TestExecutionListeners({ DependencyInjectionTestExecutionListener.class, DirtiesContextTestExecutionListener.class,
        TransactionalTestExecutionListener.class, DbUnitTestExecutionListener.class })
@DatabaseSetup(value = { "/datasets/dataset1.xml", "/datasets/dataset2.xml" })
public class myTestIT {

    @Autowired
    private ClassUnderTest classUnderTest;


    @Test
    public void test() {
         ...
    }

}

This is the bean that queries the DB inside @PostConstruct:

public class MyBean {
    @Autowire
    private SomeService someService;

    private List someList;

    @PostConstruct
    public void init()  {
         someList = someService.queryDB();
    }
}

This is an example of the class I want to test

public class ClassUnderTest {
    @Autowire
    private MyBean bean;


    public void methodToTest() {
        bean.getSomeList();
        // do Something
    }
}
felipe_gdr
  • 1,088
  • 2
  • 11
  • 27
  • Yes, it is definitely possible. Can you show us some details? – Dakota Brown Sep 03 '14 at 13:03
  • 2
    so is classUnderTest the class that needs to query in the @PostConstruct? I don't see a MyBean anywhere. For starters, you won't be able to use the @DatabaseSetup because autowiring will happen first--you'll have to configure a org.dbunit.DataSourceDatabaseTester bean – Dakota Brown Sep 03 '14 at 13:50
  • ok, I've included more code in my question. – felipe_gdr Sep 03 '14 at 14:00
  • 1
    did you find an answer on how to do this? I have the same question, but haven't really figured out how to do it yet; – froginvasion Dec 10 '14 at 18:58
  • I did not find an answer to this yet – felipe_gdr Dec 10 '14 at 19:10
  • For now i solve autowiring beans in my test class and in the @before method, calling beans postconstruct method again. This is not the best way and i'm searching for a better aproach too. With Unitils i could do this =(. – Sandro Simas Apr 28 '15 at 15:02
  • I'm having the same issue, one of my service retrieve database in his @postconstruct method and thus cant find the table and breaks ... – TheBakker Sep 04 '15 at 09:47

0 Answers0