最小起订量界面与动作 属性
Moq Interface with Action property
我目前正在使用 Fleck 框架,我想模拟界面 IWebSocketConnection
。它有一些 属性 类型 Action
,我想 raise 论文 events.
到目前为止,我尝试将其作为这样的事件提出来但没有成功:
fleckInterfaceMock.Raise(mock => mock.OnClose += null);
甚至可以像这样直接调用它:
fleckInterfaceMock.Object.OnClose();
上没有发现任何有趣的内容
界面:
namespace Fleck
{
public interface IWebSocketConnection
{
IWebSocketConnectionInfo ConnectionInfo { get; }
bool IsAvailable { get; }
Action<byte[]> OnBinary { get; set; }
Action OnClose { get; set; }
Action<Exception> OnError { get; set; }
Action<string> OnMessage { get; set; }
Action OnOpen { get; set; }
Action<byte[]> OnPing { get; set; }
Action<byte[]> OnPong { get; set; }
void Close();
Task Send(byte[] message);
Task Send(string message);
Task SendPing(byte[] message);
Task SendPong(byte[] message);
}
}
请注意,OnClose
和接口中的其他成员实际上并不是事件。它们实际上是 get
-set
属性,其 属性 类型恰好是委托类型。
因此,我认为您不能或不应使用起订量的 Raise
。
如果你想要调用:
// desired use
fleckInterfaceMock.Object.OnClose();
要成功,需要 get
访问器 return 非空 Action
。
你可以这样做:
// possible Moq setup
Action a = () => { Console.WriteLine("Testing OnClose."); };
fleckInterfaceMock.Setup(x => x.OnClose).Returns(a);
如果您想要以下类型的委托组合(这不是真正的事件订阅;我们没有事件):
// desired use
fleckInterfaceMock.Object.OnClose += someAction;
要成功,模拟必须首先像以前一样容忍 get
的 属性,其次它必须容忍 set
和 属性(它将 set
到 (1) 由 get
编辑的 return 和 (2) someAction
.
的 "sum"
您可以通过多种方式实现这一目标。一种方法很简单:
// possible Moq setup
fleckInterfaceMock.SetupProperty(x => x.OnClose);
这将简单地将 OnClose
变成一个 属性,它允许 get
和 set
,并且它会记住它是什么 set
并给出当调用 get
时该值返回。
我目前正在使用 Fleck 框架,我想模拟界面 IWebSocketConnection
。它有一些 属性 类型 Action
,我想 raise 论文 events.
到目前为止,我尝试将其作为这样的事件提出来但没有成功:
fleckInterfaceMock.Raise(mock => mock.OnClose += null);
甚至可以像这样直接调用它:
fleckInterfaceMock.Object.OnClose();
上没有发现任何有趣的内容
界面:
namespace Fleck
{
public interface IWebSocketConnection
{
IWebSocketConnectionInfo ConnectionInfo { get; }
bool IsAvailable { get; }
Action<byte[]> OnBinary { get; set; }
Action OnClose { get; set; }
Action<Exception> OnError { get; set; }
Action<string> OnMessage { get; set; }
Action OnOpen { get; set; }
Action<byte[]> OnPing { get; set; }
Action<byte[]> OnPong { get; set; }
void Close();
Task Send(byte[] message);
Task Send(string message);
Task SendPing(byte[] message);
Task SendPong(byte[] message);
}
}
请注意,OnClose
和接口中的其他成员实际上并不是事件。它们实际上是 get
-set
属性,其 属性 类型恰好是委托类型。
因此,我认为您不能或不应使用起订量的 Raise
。
如果你想要调用:
// desired use
fleckInterfaceMock.Object.OnClose();
要成功,需要 get
访问器 return 非空 Action
。
你可以这样做:
// possible Moq setup
Action a = () => { Console.WriteLine("Testing OnClose."); };
fleckInterfaceMock.Setup(x => x.OnClose).Returns(a);
如果您想要以下类型的委托组合(这不是真正的事件订阅;我们没有事件):
// desired use
fleckInterfaceMock.Object.OnClose += someAction;
要成功,模拟必须首先像以前一样容忍 get
的 属性,其次它必须容忍 set
和 属性(它将 set
到 (1) 由 get
编辑的 return 和 (2) someAction
.
您可以通过多种方式实现这一目标。一种方法很简单:
// possible Moq setup
fleckInterfaceMock.SetupProperty(x => x.OnClose);
这将简单地将 OnClose
变成一个 属性,它允许 get
和 set
,并且它会记住它是什么 set
并给出当调用 get
时该值返回。