I create a service host class in my tests project that on AssemblyInitialize of the test project, self hosts the service I wish to invoke.
[TestClass]
internal class ServiceHost
{
private static ServiceHost<Service1> m_Host = null;
/// <summary>
/// Setups the specified context.
/// </summary>
/// <param name="context">The context.</param>
[AssemblyInitialize]
public static void Setup(TestContext context)
{
//comment to run against local consolehost
m_Host = new ServiceHost<Service1>();
m_Host.Open();
}
/// <summary>
/// Tears down.
/// </summary>
[AssemblyCleanup]
public static void TearDown()
{
if (m_Host != null)
{
m_Host.Close();
}
}
}
In the test I use ChannelFactory to invoke the service. I then close the service on AssemblyCleanup.
try
{
ChannelFactory<IService> factory = new ChannelFactory<IService>("User");
IServiceproxy = factory.CreateChannel();
try
{
m_IsAuthenticated = proxy.Method("");
// Make sure to close the proxy
(proxy as IClientChannel).Close();
Assert.IsTrue(m_IsAuthenticated);
}
catch
{
if (proxy != null)
{
// If the proxy cannot close normally or an exception occurred, abort the proxy call
(proxy as IClientChannel).Abort();
}
throw;
}
}
catch (Exception ex)
{
Assert.Fail(ex.Message);
}
Give the test project its own App.config file with relevant settings so that when it hosts it is relevant to the test environment. This gives you an automated black box test. I also use Mocks to isolate the part of the service I wish to test.