0
public interface Animal {
    public String getName();
    public int getAge();
}

@Component
public class Dog implements Animal{

    @Override public String getName() {
        return "Puppy";
    }

    @Override public int getAge() {
        return 10;
    }
}

@Component("cdiExample")
public class CDIExample {
    @Autowired
    private Dog dog;

    public void display() {
        try {
            System.out.println("com.example.Animal ---> " + dog.getName());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

        public static void main(String[] args) {
            ApplicationContext context = new ClassPathXmlApplicationContext("classpath*:beans.xml");
            Animal animal=context.getBean("dog", Animal.class);
            System.out.println(animal.getName());
        }
    }

Application Context

 <context:annotation-config/>
 <context:component-scan base-package="com.example"/>

Junit Test

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = { "classpath*:test-beans.xml" })
public class CDIExampleTest {

    //@Autowired
    private CDIExample cdiExample;

    @Before
    public void before() throws Exception {
        cdiExample = new CDIExample();
    }

    @Test
    public void testDisplay() throws Exception {
        cdiExample.display();

    }

} 

Test-context

<import resource="classpath*:/beans.xml" />

If i run the above Junittestcase, autowire is null.

If i execute the main method and Using ClassPathXmlApplicationContext, bean is loading and autowire is not null.

arulprakash
  • 22
  • 1
  • 6
  • It cannot be null as spring will throw an exception if it cannot be auto wired. So you must be having something wrong in how you run your testcase. – M. Deinum May 25 '15 at 14:28

1 Answers1

0

the problem seems to be cdiExample in you test case not being a spring bean. You are manually instantiating it in @Before.

Instead try this:

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = { "classpath*:test-beans.xml" })
public class CDIExampleTest {

    @Autowired
    private CDIExample cdiExample;

    @Test
    public void testDisplay() throws Exception {
        cdiExample.display();

    }

} 

This way the cdiExample will be injected from the spring context which will have dog autowired by spring.

Bharath
  • 259
  • 1
  • 13