哇,经过两天的艰苦努力,我终于找到了一个令我满意的解决方案:
如上面的代码示例所示,我使用这个辅助类来管理我的WCF连接(因为它能正确处理Close和Abort):
public delegate void UseServiceDelegate<T>(T proxy);
public static class Service<T>
{
public static ChannelFactory<T> _channelFactory;
public static void Use(UseServiceDelegate<T> codeBlock)
{
if (_channelFactory == null)
_channelFactory = new ChannelFactory<T>("AlyzaServiceEndpoint");
IClientChannel proxy = (IClientChannel)_channelFactory.CreateChannel();
bool success = false;
try
{
codeBlock((T)proxy);
proxy.Close();
success = true;
}
finally
{
if (!success)
{
proxy.Abort();
}
}
}
}
如您所见,这是在我的ViewModel中使用此类的方式:
Service<Sam.Alyza.WcfInterface.IServiceWebsites>.Use(alyzaSvc =>
{
rc = new List<Sam.Alyza.WcfInterface.Website>(alyzaSvc.GetSites());
});
要模拟 WCF 接口,我需要创建和托管一个模拟的 WCF 服务,并更改所有连接字符串。这是为了添加一些测试而需要做很多工作。
我找到了一个更简单的方法:
只需实现该接口便可创建模拟服务:
public class MockWebsiteService : WcfInterface.IServiceWebsites
{
internal List<Sam.Alyza.WcfInterface.Website> _websites = new List<Sam.Alyza.WcfInterface.Website>();
internal int _GetSitesCallCount;
IEnumerable<Sam.Alyza.WcfInterface.Website> Sam.Alyza.WcfInterface.IServiceWebsites.GetSites()
{
_GetSitesCallCount++;
return _websites;
}
}
唯一的问题是:我该如何使ViewModel调用这个模拟类而不是服务?
解决方案:Service.Use() 确实管理连接。通过添加覆盖连接管理的功能,我可以将自己的 WCF 模拟对象潜入 Service.Use() 中。
为此,我需要一种方法来让 Service.Use() 调用其他东西而不是 WCF(请查看#DEBUG部分):
public static class Service<T>
{
#if DEBUG
public static T DebugOverride = default(T);
#endif
public static ChannelFactory<T> _channelFactory;
public static void Use(UseServiceDelegate<T> codeBlock)
{
#if DEBUG
if (!Object.Equals(DebugOverride, default(T)))
{
codeBlock(DebugOverride);
return;
}
#endif
if (_channelFactory == null)
_channelFactory = new ChannelFactory<T>("AlyzaServiceEndpoint");
IClientChannel proxy = (IClientChannel)_channelFactory.CreateChannel();
bool success = false;
try
{
codeBlock((T)proxy);
proxy.Close();
success = true;
}
finally
{
if (!success)
{
proxy.Abort();
}
}
}
}
通过在Service中添加此测试钩子,我能够在我的测试中插入任何实现T的对象。
MockWebsiteService mockmodel = new MockWebsiteService()
Service<WcfInterface.IServiceWebsites>.DebugOverride = mockmodel
// run my tests here
对我来说,这是一个非常好的模拟WCF服务的方法!
PS:由于#if DEBUG,测试在发布时不会编译。如果你关心的话,就将它们踢出去。