VB_
VB_

Reputation: 45692

Spring injection tricks

I have: injecting MyClass and String objects into Utils at constructor.

Questions:

  1. How does it works when in Utils bean definition (look at beans definition section) I mentioned only the second argument of Utils constructor?
  2. How to pass MyClass mock into Utils object in unit tests? I mean how to redefine the bean definition?

Utils.java

public class Utils {
    @Inject
    public Utils(MyClass obj, String val) {
        this.obj = obj;
        this.val = val;
    }

Beans definition:

<bean class="com.mypack.MyClass"/>

<bean id="utils" class="com.mypack.Utils">
    <constructor-arg value="bucket" />
</bean>

Upvotes: 0

Views: 111

Answers (1)

Evgeni Dimitrov
Evgeni Dimitrov

Reputation: 22496

You can define define another(test) context for the unit tests:

    @RunWith(SpringJUnit4ClassRunner.class)
    @ContextConfiguration(locations = { "my-test-context.xml",
                                        "some-other-context.xml" })
    public class SkipSampleFunctionalTests {

        @Autowired
        private SomeBean bean;

    ...
    }

If you want to override only one bean, you can import your main(core) context int the test context and change only the desired bean:

<import resource="main-context.xml"/>
<bean id="x" class="com.asd.MyClass">
     <property name="y" ref="y"/>
</bean> 

Upvotes: 1

Related Questions