Using Spring autowired bean from other project in JUnit

时间:2015-09-22 12:53:58

标签: spring maven junit dependencies autowired

I'm writing unit tests for my app consisting of several projects. I have project A for which I'm writing tests, and project B where I want to store some needed beans to be autowired in A test classes. Prject A also needs B in the compilation scope.

If using dependency like that:

...
A/pom.xml
...
<dependency>
    <artifactId>B</artifactId>
    <scope>compile</scope>
<dependency>

spring is unable to autowire beans of B project. It's strange, because according to the Maven docs, compile scope also makes project content available at the stage phase.

In case I use the save dependency but with test scope, unit tests work, but app itself faild (pretty predictable).

In case when I use both dependencies, like:

...
A/pom.xml
...
<dependency>
    <artifactId>B</artifactId>
    <scope>compile</scope>
<dependency>

<dependency>
    <artifactId>B</artifactId>
    <scope>compile</scope>
    <type>test-jar</type>
    <scope>test</scope>
<dependency>

mvn clean install fails since it's unable to resolve dependencies.

So what can I do? Is there any best practise of using other project beans in unit tests in Spring?

2 个答案:

答案 0 :(得分:0)

默认的maven范围(编译)应该这样做。应该允许您在编译/测试时访问类。

你应该看看:

  • 你为每个项目使用什么包装(jar / war)
  • 你如何自动将bean从B自动装配到A,自动装配是否在运行时工作,
  • 也许在测试时间VS运行时
  • 创建Spring上下文的方式有所不同
  • 可能是Spring自动扫描机制没有扫描B项目包(至少在测试中)

答案 1 :(得分:0)

我们通常这样做: <dependency> <artifactId>B</artifactId> <groupId>groupID</groupId> <version>version number</version> <scope>compile</scope> <type>jar or war</type> </dependency>