【发布时间】:2011-02-26 08:50:38
【问题描述】:
我最近开发了一个 Silverlight 应用程序,它使用 Mark J Millers ClientChannelWrapper<T> 与 WCF 服务层通信(有效地终止服务引用并包装 IClientChannel 和 ClientChannelFactory)。
界面如下:
public interface IClientChannelWrapper<T> where T : class
{
IAsyncResult BeginInvoke(Func<T, IAsyncResult> function);
void Dispose();
void EndInvoke(Action<T> action);
TResult EndInvoke<TResult>(Func<T, TResult> function);
}
Wrapper 基本上采用通用异步服务接口(可能由 slsvcutil 生成或在 WCF ServiceContract 之后手工制作)并包装调用以确保在发生通道故障时创建新通道。
典型用法如下所示:
public WelcomeViewModel(IClientChannelWrapper<IMyWCFAsyncService> service)
{
this.service = service;
this.synchronizationContext = SynchronizationContext.Current ?? new SynchronizationContext();
this.isBusy = true;
this.service.BeginInvoke(m => m.BeginGetCurrentUser(new AsyncCallback(EndGetCurrentUser), null));
}
private void EndGetCurrentUser(IAsyncResult result)
{
string strResult = "";
service.EndInvoke(m => strResult = m.EndGetCurrentUser(result));
this.synchronizationContext.Send(
s =>
{
this.CurrentUserName = strResult;
this.isBusy = false;
}, null);
}
一切正常,但现在我想对使用ClientChannelWrapper 的视图模型进行单元测试。
我已经使用 Moq 设置了一个简单的单元测试:
[TestMethod]
public void WhenCreated_ThenRequestUserName()
{
var serviceMock = new Mock<IClientChannelWrapper<IMyWCFAsyncService>>();
var requested = false;
//the following throws an exception
serviceMock.Setup(svc => svc.BeginInvoke(p => p.BeginGetCurrentUser(It.IsAny<AsyncCallback>(), null))).Callback(() => requested = true);
var viewModel = new ViewModels.WelcomeViewModel(serviceMock.Object);
Assert.IsTrue(requested);
}
我得到一个 NotSupportedException:
不支持的表达式:p => p.BeginGetCurrentUser(IsAny(), null)。
我对 Moq 还很陌生,但我想 ClientChannelWrapper 使用通用服务接口存在一些问题。想把我的脑袋绕过去很长一段时间,也许有人有想法。谢谢。
【问题讨论】:
标签: wcf unit-testing moq channelfactory