I am using Spring framework 3.0.5 to build a web application. I use the @Configuration annotation to configure my domain object, and some domain objects have a session scope. And when I write unit test using jUnit 4.8.2, the AnnotationConfigWebApplicationContext variable cannot get the beans that are defined in the configuration class.
I get the following exceptions:
org.springframework.beans.factory.NoSuchBeanDefinitionException: No bean named 'country' is defined
Is there anyone who can give me advice on this issue? Thank you very much!
Here is my configuration class, unit test class, DAO class and domain object class. (I use annotation to configure the application instead of xml)
Configuration class:
@Configuration public class RegionDomainObj { @Bean @Scope("session") public CityImp city() { return new CityImp(); } @Bean @Scope("session") public CityIPImp cityIP() { return new CityIPImp(); } @Bean @Scope("session") public CountryImp country() { return new CountryImp(); } @Bean @Scope("session") public CountryIPImp countryIP() { return new CountryIPImp(); } @Bean @Scope("session") public LocaleImp locale() { return new LocaleImp(); } @Bean @Scope("session") public RegionImp region() { return new RegionImp(); } @Bean @Scope("session") public TopLevelDomainImp topLevelDomain() { return new TopLevelDomainImp(); } }
Test class:
@RunWith(SpringJUnit4ClassRunner.class) public class TestENV { protected AnnotationConfigWebApplicationContext annotationConfigWebApplicationContext; @Before public void setUp() { annotationConfigWebApplicationContext = new AnnotationConfigWebApplicationContext(); annotationConfigWebApplicationContext.refresh(); } }
Unit Test class:
public class CountryDAOTest extends TestENV { private ICountryDAO countryDAO; private ICountry country; @Before public void setUpLocalTestENV() { this.country = (ICountry) this.annotationConfigWebApplicationContext.getBean("country"); this.countryDAO = (ICountryDAO) this.annotationConfigWebApplicationContext.getBean("crazyamsCountryDAO"); } @Test public void testSaveCountry() { this.country.setCode("AU"); this.country.setName("Australia"); this.countryDAO.save(this.country); } }
Update
Maybe I am making this problem too complicated, you know, when we use AnnotationConfigApplicationContext , we can use the following code to register bean definitions.
AnnotationConfigApplicationContext annotationConfigApplicationContext = new AnnotationConfigApplicationContext(); annotationConfigApplicationContext.register(TestProcessUnitConfig.class, OtherClazz.class);
And in my project I use Spring MVC with annotation support, and instead of AnnotationConfigApplicationContext use AnnotationConfigWebApplicationContext .
Although they are very similar, AnnotationConfigWebApplicationContext does not provide a "register" function.
And I just want to know if there is another way to register the bean definition in AnnotationConfigWebApplicationContext or not.