开发者

Override WCF Client Methods

开发者 https://www.devze.com 2023-04-06 22:21 出处:网络
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 t

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'开发者_Python百科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?


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:

public interface IWcfInterface {
     string[] GetTheNames();
}

And your application logic class looks like:

public class ApplicationLogic {

     public IWcfInterface WcfInterface {get;set;}

     public SomeLogic() {
         WcfInterface.GetTheNames();
     } 
}

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:

public FakeImplementation : IWcfInterface {
     public string[] GetTheNames() {
         return new string[] { "foo", "bar" };
     }
}


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.

public class BaseC
{
    public int x;
    public void Invoke() { }
}
public class DerivedC : BaseC
{
    new public void Invoke() { }
}
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号