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 whe
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.
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.
You should use the SpringJUnit4ClassRunner
on your test classes, and use @Resource
(or @Autowired
) on the field in your test class that contains the bean. You should consider having a special test context Spring configuration that uses stubs so that your tests are genuine unit tests, and don't rely on the whole application context.