1
votes

I'm using junit to test some one of my services. I use spring to inject the service and all it's dependencies. My test class looks like the folowing.

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = {"classpath:/location/MyServiceTest-context.xml"})
@Transactional
public class MyServiceTest extends TestSupport {

    @Autowired
    private MyService myService;

    @Test
    public void testX() throws Exception {
        ...
    }
}

The configuration file is:

<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:context="http://www.springframework.org/schema/context"
       xsi:schemaLocation="http://www.springframework.org/schema/beans      
       http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
       http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd">


     <bean id="entityBasePackages" class="java.lang.String">
         <constructor-arg value="com.package1.model"/>
     </bean>

     <bean id="bean1" class="org.easymock.EasyMock" factory-method="createMock">
         <constructor-arg value="com.package2.bean1"/>
     </bean>

     <bean id="bean2" class="org.easymock.EasyMock" factory-method="createMock">
         <constructor-arg value="com.package3.bean2"/>
     </bean>

     <context:component-scan base-package="com.package4.MyService"/>

 </beans>

MyService uses a bean1. bean1 depends on bean2, that is, it uses it. When i run my test like this, it works fine. However, if i declare bean2 above bean1 in my configuration xml, the test fails with a

org.springframework.beans.factory.NoSuchBeanDefinitionException: No matching bean of type [com.package2.bean1]

I guess Spring reads the file and when it gets to a bean definition, tries to wire it - that's why it crashes in my case. Is there a way to tell Spring to read the entire file and then try to wire the beans? This way i could write my bean definitions without worrying about their order. Thanks

1
Order should not matter! Spring does not try to wire immediately, it creates a metadata from the the available configuration(bean definitions) and then starts wiring the beans together. You said bean1 depends on bean2, but here both appear to be mocks right? can you show the configuration where you wire the mocks together - Biju Kunjummen

1 Answers

0
votes

I realize bean1 and bean2 were not the best chosen names. But here is how i'm using them:

@Service("bean1")
public class Bean1{

    ...

    @Validators(value = {
            @Validator(validatorClass = Bean2.class, parameters = {@Parameter(0)}, shortCircuit = true)})
    public void someMethod(SomeObject someObject){
         ...
    }

    ...
}

MyService uses internally a bean1 service.