Spring not autowiring in unit tests with JUnit

后端 未结 5 735
盖世英雄少女心
盖世英雄少女心 2020-12-03 02:33

I test the following DAO with JUnit:

@Repository
public class MyDao {

    @Autowired
    private SessionFactory sessionFactory;

    // Other stuff here

}
         


        
5条回答
  •  青春惊慌失措
    2020-12-03 03:10

    You need to add annotations to the Junit class, telling it to use the SpringJunitRunner. The ones you want are:

    @ContextConfiguration("/test-context.xml")
    @RunWith(SpringJUnit4ClassRunner.class)
    

    This tells Junit to use the test-context.xml file in same directory as your test. This file should be similar to the real context.xml you're using for spring, but pointing to test resources, naturally.

提交回复
热议问题