Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

spring junit testing

I have a maven spring project (latest version) and I want to write some junit tests (latest version).

The issue I have is that my spring beans are autowired, and when I call them from junit test, I get null pointer exceptions, as spring doesn't autowire them.

How can I load the context so that things are autowired?

like image 772
Massive Boisson Avatar asked Jul 01 '11 10:07

Massive Boisson


2 Answers

Have you studied Testing chapter in Spring reference documentation? Here is an example you should start with:

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration
public class MyTest {

    @Resource
    private FooService fooService;

    // class body...
}

If you are in com.example.MyTest in /src/test/java, you will need /src/test/resources/com/example/MyTest-context.xml - but the exceptions will show you the way.

like image 129
Tomasz Nurkiewicz Avatar answered Oct 04 '22 21:10

Tomasz Nurkiewicz


This is a possibility:

@RunWith(SpringJUnit4ClassRunner.class)
// ApplicationContext will be loaded from "/applicationContext.xml"
// in the root of the classpath
@ContextConfiguration({"/applicationContext.xml"})
public class MyTest {
// class body...
}

Usually it's a good idea though to have a test-applicationContext for your test infrastructure.

like image 43
abalogh Avatar answered Oct 04 '22 22:10

abalogh