我的項目需要在CruiseControl中自動化的測試WEB服務,測試需滿足下列條件:
* 不依賴於IIS
* 不對WebService做部署,直接在其CC編譯的組建目錄中運行WEB服務
如果滿足以上需求,當然也可以使用相同方式在VS和CC裡測試網頁。
在網上找到了SCOTT的文章NUnit Unit Testing of ASP.NET Pages, Base Classes, Controls and other widgetry using Cassini (ASP.NET Web Matrix/Visual Studio Web Developer),使用Cassini來做果然方便。
自己寫了個協助類(見頁尾),然後這樣使用(在TestFixtureSetUp中運行Cassini,返回其服務地址給測試使用): [TestFixtureSetUp]
public void Init()
{
_cassni = new CassiniHelper();
_cassni.Start();
//你可如此獲得Cassini運行起來的WEB服務地址
//config.CurrentServiceEntryUrl = _cassni.WebServerUrl;
}
[TestFixtureTearDown]
public void FixtureTearDown()
{
_cassni.Close();
}
- CassiniHelper internal class CassiniHelper
{
private int _webServerPort = 26610;
private Server _webServer;
private readonly string _webServerVDir = "/ws";
private string _workingPath;
private string _webServerUrl;
private string _abstractPathFromTestToWebService = @"..\..\..\WebService";
public CassiniHelper()
{
SetWebServerUrl();
}
public int WebServerPort
{
get { return _webServerPort; }
set
{
_webServerPort = value;
SetWebServerUrl();
}
}
public string WebServerUrl
{
get { return _webServerUrl; }
set { _webServerUrl = value; }
}
/**//// <summary>
/// 從測試案常式序集所在目錄到WEBServer所在目錄的相對路徑
/// </summary>
public string AbstractPathFromTestToWebService
{
get { return _abstractPathFromTestToWebService; }
set { _abstractPathFromTestToWebService = value; }
}
/**//// <summary>
/// WEB服務的虛擬路徑
/// </summary>
public string WebServerVDir
{
get { return _webServerVDir; }
}
public void Start()
{
if(!Directory.Exists(_workingPath))
throw new DirectoryNotFoundException(_workingPath);
_webServer = new Server(_webServerPort, WebServerVDir, _workingPath);
_webServer.Start();
}
public void Close()
{
try
{
if (_webServer != null)
{
_webServer.Stop();
_webServer = null;
}
}
catch { }
}
private void SetWebServerUrl()
{
string currentPath = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
DirectoryInfo dinfo = new DirectoryInfo(Path.Combine(currentPath, _abstractPathFromTestToWebService));
_workingPath = dinfo.FullName;
//拷貝Cassini.dll到web服務的bin目錄下
string cassini = "Cassini.dll";
File.Copy(Path.Combine(currentPath, cassini), Path.Combine(Path.Combine(_workingPath,"bin"),cassini));
_webServerUrl = String.Format("http://localhost:{0}{1}", _webServerPort, WebServerVDir);
}
}