春季junit测试

Mas*_*son 8 java junit spring unit-testing

我有一个maven spring项目(最新版本),我想写一些junit测试(最新版本).

我的问题是我的spring bean是自动装配的,当我从junit测试中调用它们时,我得到空指针异常,因为spring不会自动装配它们.

如何加载上下文以便自动连接?

Tom*_*icz 21

你有没有学过Spring参考文档中的测试章节?这是一个你应该开始的例子:

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

    @Resource
    private FooService fooService;

    // class body...
}
Run Code Online (Sandbox Code Playgroud)

如果你com.example.MyTest/src/test/java,你将需要/src/test/resources/com/example/MyTest-context.xml- 但例外将告诉你的方式.

  • 这解决了这个问题:<plugins> <plugin> <groupId> org.apache.maven.plugins </ groupId> <artifactId> maven-surefire-plugin </ artifactId> <configuration> <additionalClasspathElements> <additionalClasspathElement> $ {basedir}/src/main/webapp/WEB-INF/</ additionalClasspathElement> </ additionalClasspathElements> </ configuration> </ plugin> </ plugins> (2认同)

aba*_*ogh 12

这是一种可能性:

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

通常,为测试基础架构提供test-applicationContext是个好主意.


art*_*tol 5

您应该SpringJUnit4ClassRunner在测试类上使用,并在包含该bean的测试类中的字段上使用@Resource(或@Autowired).您应该考虑使用特殊的测试上下文Spring配置,它使用存根,以便您的测试是真正的单元测试,而不是依赖于整个应用程序上下文.