[英]“Simple” Spring unit tests
我正在嘗試為繼承的基於Spring
的項目配置單元測試。 我已經嘗試了一些方法,但是基本上我在嘗試將@Autowired
東西塞入我的測試用例中時陷入了困境。 這是我的設置:
如下所示的控制器類:
@Controller("serverService")
@RequestMapping("/rest/server")
@Api(value = "server")
public class ServerServiceImpl extends AbstractServiceImpl implements ServerService {
@Override
@RequestMapping(value = "/getTime", method = RequestMethod.GET)
public @ResponseBody
GatewayResponse<TimeData> getTime() {...}
ServerService
只是一個允許與GWT
互操作的接口。 我現在不太擔心GWT
單元測試。
AbstractServiceImpl
的主要目的是包裝基於SOAP
的Web服務,該服務器實際上是代理服務器並使移動設備友好。 該Web服務由Apache CXF
自動生成。 (大致) AbstractServiceImpl
如下:
public class AbstractServiceImpl {
@Autowired
private WebServices webServices;
public WebServices getWebServices() {
return webServices;
}
在我的測試課中,我有:
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = {"classpath:**/applicationContext.xml", "classpath:**/applicationContext-Services.xml"})
@WebAppConfiguration
public class LoginTest {
@Autowired
private ServerServiceImpl svc;
public LoginTest() {
}
@Test
public void validate() {
assertNotNull(svc);
}
}
我對嘗試使用模擬JSON等創建對我的Web服務的模擬調用沒有興趣。 我只想編寫單元測試,以使用未模擬的WebServices
對象創建未模擬的ServerServiceImpl
並調用實時服務器。
我的測試當前失敗,因為@Autowired
無法創建ServerServiceImpl
。 我還嘗試過將代碼重構為對WebServices
使用@Autowired
並將其傳遞給ServerServiceImpl
的構造函數,但是由於@Autowired
,該操作也會失敗。
事實證明,這非常簡單。 如果為應用程序上下文指定了不存在的路徑,Spring將拋出錯誤,例如:
@ContextConfiguration("classpath:does-not-exist.xml")
上面將創建一個很好的簡單錯誤消息,告訴您問題出在哪里,即找不到文件異常。 另一方面,此代碼不會:
@ContextConfiguration("classpath:**/does-not-exist.xml")
所以我的問題很簡單,就是Spring無法找到應用程序上下文XML。 最終,我復制了實時上下文,將其扔到src/test/resources
並如下更新了pom.xml
的@ContextConfiguration
surefire-plugin
和@ContextConfiguration
:
<addtionalClasspathElements>
<addtionalClasspathElement>${basedir}/src/test/resources</addtionalClasspathElement>
</addtionalClasspathElements>
@ContextConfiguration(locations = { "classpath:applicationContext.xml", "classpath:applicationContext-Services.xml" })
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.