重写WCF客户端方法
我有一个在我的应用程序中使用的 WCF 服务。一切都工作得很好,但我试图创建一些具有相同 API 的测试类,但避免访问服务器来获取其信息。例如:
// Goes to the server to get a list of names. It might be a while.
MyClient client = new MyClient();
string[] theNames = client.GetSpitefulUsers();
...
// This is what I would use in a test case...
public FakeClient : MyClient
{
...
public override string[] GetSpitefulUsers()
{
// This returns almost immediately, but I can't just override it because the
// 'MyClient' definition is generated code.
return new string[] {"Aldo", "Barry", "Cassie"};
}
}
那么提供此类功能而无需诉诸巧妙的技巧、模拟库等的最简单方法是什么?
I have a WCF service that I use in one of my applications. Everything is working just fine, but I am trying to create some test classes that have the same API, but avoid the trip to the server to get their information. For example:
// Goes to the server to get a list of names. It might be a while.
MyClient client = new MyClient();
string[] theNames = client.GetSpitefulUsers();
...
// This is what I would use in a test case...
public FakeClient : MyClient
{
...
public override string[] GetSpitefulUsers()
{
// This returns almost immediately, but I can't just override it because the
// 'MyClient' definition is generated code.
return new string[] {"Aldo", "Barry", "Cassie"};
}
}
So what is the easiest way to provide this type of functionality without having to resort to clever hacks, mocking libraries, etc?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
WCF 服务引用有一个接口,因此所有逻辑都应该引用该接口,而不是服务客户端。在这种情况下,您将能够选择将哪种实现(真实的或虚假的)传递给您的应用程序逻辑。
假设您的 WCF 服务接口是这样的:
您的应用程序逻辑类如下所示:
因此,如果您需要真正的实现,您只需将其传递给应用程序逻辑的 WcfInterface 属性(通常这会执行依赖项注入容器)。
假的实现看起来也很简单:
WCF service reference has an interface, so all your logic should refer to that interface, not service client. In such case, you will be able to choose, what implementation(real or fake) to pass to your application logic.
Let's say your WCF service interface is this:
And your application logic class looks like:
So in case you need real implementation, you just pass it to WcfInterface property of your application logic (usually this does dependency injection container).
Fake implementation will also look simple:
如果我是对的,编译器会建议使用关键字 new 代替。
http://msdn.microsoft.com/en-us/library/435f1dw2.aspx
这个 msdnpage 将解释如何使用它。
if i am right the compiler will suggest to use the keyword new instead.
http://msdn.microsoft.com/en-us/library/435f1dw2.aspx
This msdnpage will explain how to use it.