Often you will have tests written that hit a service that is going to be hosted via IIS. On our development box we will probably be using the development webserver that ships with Visual Studio. Often the development webserver is not running when we start our tests which causes a failure. To combat that we have all our service tests inherit from a base class that starts up the webserver if it is not already running. This gives us consistent testability:
[TestFixture]
public class ServiceTestBase
{
private Process process;
[TestFixtureSetUp]
public void Start()
{
if (!IsWebServerAlreadyRunning())
{
const string x86Location = @"C:\Program Files (x86)\Common Files\microsoft shared\DevServer\9.0\WebDev.WebServer.Exe";
const string non64BitSystemLocation = @"C:\Program Files\Common Files\microsoft shared\DevServer\9.0\WebDev.WebServer.Exe";
//create a normalized path (Path.GetFullPath() will remove our ..\ characters
string physicalPath = Path.GetFullPath(Path.Combine(Environment.CurrentDirectory, "..\\..\\..\\Dispatch.Service\\"));
process = new Process();
if (File.Exists(x86Location))
process.StartInfo.FileName = x86Location;
else if (File.Exists(non64BitSystemLocation))
process.StartInfo.FileName = non64BitSystemLocation;
else
throw new FileNotFoundException("Could not find WebDev.WebServer.Exe");
process.StartInfo.Arguments = string.Format("/port:{0} /virtual:\"\" /path:\"{1}\\\"", 50256, physicalPath);
process.StartInfo.CreateNoWindow = true;
process.StartInfo.UseShellExecute = false;
// start the web server
process.Start();
}
}
private static bool IsWebServerAlreadyRunning()
{
Process[] processes = Process.GetProcessesByName("WebDev.WebServer.Exe");
if (processes.Length > 1)
return true;
return false;
}
//if you want to stop the webserver after each test fixture is run then
//uncomment the following
//[TestFixtureTearDown]
//public void TearDown()
//{
// if (process != null)
// process.Kill();
//}
}