2013-10-21 23 views
2

我有兩個Java項目中,「A」和「B」,和B對A中的Maven的依賴關係:重用在另一個項目中的Spring測試方面

<dependency> 
    <!-- Back end stuff --> 
    <groupId>com.myapp</groupId> 
    <artifactId>ProjectA</artifactId> 
    <version>1.0.0</version> 
</dependency> 

這兩個項目由上並肩而坐我的工作站在一個共同的父文件夾:

/Myproject 
    /ProjectA 
    /ProjectB 

我想使用項目A的單元測試中,「測試的context.xml」,爲項目B我所有的單元測試,以及。有沒有辦法直接引用外部環境進行測試?這些是使用Surefire和Junit進行測試的Maven項目,但我擔心Surefire和Junit不是我的強項。我很確定有一種方法可以做到這一點,但我不知道在哪裏尋找答案--Spring,Junit,Maven,Surefire ......?

我的項目「A」單元測試類,可以這樣來配置:

@RunWith(SpringJUnit4ClassRunner.class) 
@ContextConfiguration(locations={"classpath:test-context.xml"}) 

和文件「試驗context.xml中」是項目A在/ src目錄/測試/資源/測試環境。 XML。理想情況下,我只想配置我的項目「B」單元測試類,像這樣:

@RunWith(SpringJUnit4ClassRunner.class) 
@ContextConfiguration(locations={"ProjectA-reference:test-context.xml"}) 

不過,我不知道如何ContextConfiguration要素配置指向其他項目。有沒有人做過這個?

回答

5

在項目A的POM,這樣做是爲了產生一個測試-JAR依賴:

<build> 
    <plugins> 
     <plugin> 
      <artifactId>maven-jar-plugin</artifactId> 
      <executions> 
       <execution> 
        <goals> 
         <goal>test-jar</goal> 
        </goals> 
       </execution> 
      </executions> 
     </plugin> 
    </plugins> 
</build> 

然後,在項目B的pom.xml,這樣做:

<dependency> 
     <groupId>${project.groupId}</groupId> 
     <artifactId>ProjectA</artifactId> 
     <version>${project.version}</version> 
     <type>test-jar</type> 
     <scope>test</scope> 
    </dependency> 

最後,在你的ProjectB的測試類,您應該能夠使用上面嘗試的類路徑方法從ProjectA中的src/test/resources中引用任何xml文件。假設你的文件被稱爲projectA-test-context.xml並駐留在/ src/test/resources/META-INF/spring中。

@RunWith(SpringJUnit4ClassRunner.class) 
@ContextConfiguration("/META-INF/spring/projectA-test-context.xml") 

編輯編輯我的答案改正/ src目錄/主/資源/ src目錄/測試/資源。

+0

如果從兩個項目中引用單個XML文件,那麼將它移動到某個公共位置就不太合理了,如項目C –

+0

這是另一種選擇,但引用它的過程與我的答案中的過程相同。通用文件可以放在「ProjectTest」或一些類似命名的模塊中,而不是「ProjectA」。我的答案中唯一的調整是在依賴項中,將「ProjectA」更改爲「ProjectTest」。 – MattSenter

+1

這工作很好。謝謝! – user1071914

相關問題