以编程方式运行Web服务器:
在上例中我们需要运行WebServer,要么是通过命令行工具,要么是通过运行Web项目。但有时我们需要单元测试项目能够动态打开一个WebServer。一起来看看。
首先,如果你需要打开ASP.NET内部服务器(WebDev.WebServer),可以使用命令行。语法如下:
WebDev.WebServer.exe /port:1950 /path:"C:\Projects\MyWebApplication"
需要定位到WebDev.WebServer所在的目录,默认情况下它在:
C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\WebDev.WebServer.exe
好了,现在来看看如何在单元测试中打开服务器。首先,添加必要的配置(App.config中)。
<configuration>
<appSettings>
<add key="WebServerExePath" value="C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\WebDev.WebServer.exe"/>
<add key="Port" value="4463"/>
<add key="WebApplicationPath" value="c:\projects\demowatiN\demowatiN" />
<add key="DefaultPageUrl" value="http://localhost:4463/Default.aspx" />
</appSettings>
</configuration>
BaseTestPage类可以通过这些信息运行服务器,所有继承了它的测试类都可以使用这个功能了。
下面是BaseTestPage类的完整代码:
public class BaseTestPage
{
static Process server = null;
static BaseTestPage()
{
if (Process.GetProcessesByName("WebDev.WebServer").Length == 0)
{
string webServerExePath = (string)ConfigurationManager.AppSettings["WebServerExePath"];
server = new Process();
Process.Start(webServerExePath, GetWebServerArguments());
}
}
public static string GetWebServerArguments()
{
string args = String.Format("/port:{0} /path:\"{1}\"", GetPort(), GetWebApplicationPath());
if (String.IsNullOrEmpty(args)) throw new ArgumentNullException("Arguments is not defined");
return args;
}
public static string GetPort()
{
string port = ConfigurationManager.AppSettings["Port"] as String;
if (String.IsNullOrEmpty(port)) throw new ArgumentNullException("Port is null or empty");
return port;
}
public static string GetWebApplicationPath()
{
string webApplicationPath = ConfigurationManager.AppSettings["WebApplicationPath"] as String;
if (String.IsNullOrEmpty(webApplicationPath)) throw new ArgumentNullException("WebApplicationPath is null or empty");
return webApplicationPath;
}
}
如果服务器没有运行,我们会新建一个进程运行它,否则就使用已有的进程。GetWebServerArguments()、GetPort()和GetWebApplicationPath()仅仅是辅助方法,可以提高可读性。
最后,你可以让单元测试类继承该类:
public class TestAgreementPage : BaseTestPage
现在,运行单元测试项目时,它会运行WebServer,然后再执行所有测试。
结论:
在本文中,我们学习了如何对用户界面层进行单元测试,这些测试可帮助我们理解UI的需求,并快速地看到基于用户输入所得到的结果。而如果手动进行测试,就要花费很多时间了。