views:

69

answers:

1

Hi, guys! Now my team working on a client application(c#), and I need to call some web apis that returns xml messages. I want to test the methods that calling these web apis, I know I should use mock objects in unit test. But I can't know how to use it correctly, because this is my first time to introduce unit test to my project. Can someone give my some suggestions? Thanks!

A: 

It depends on the structure of your client application. You may need to do some refactoring.

I take it you have some classes client side that are responsible for communicating with the web API. Each of these classes should implement an interface. It is generally a good idea to have classes on the system boundaries of your application implement interfaces regardless.

NOTE: If you can't touch the code for the proxy classes, you can write an adapter that wraps the proxy class, but which implements the interface directing interface calls to the wrapped object.

E.g.

interface IClientSideWebApiAccessor
{
  // Operations that the web API should support.
}

class ClientSideWebApiAccessor : IClientSideWebApiAccessor
{
  // Implementation of IClientSideWebApiAccessor which actually accesses the web.
}

The next stage is to ensure that you can easily pass in an instance of IClientSideWebApiAccessor (or whatever your equivalent interface is) to whatever needs to access the API. E.g.

class ClientSideWebApiAccessorConsumer
{
  public ClientSideWebApiAccessorConsumer(IClientSideWebApiAccessor apiAccessor) 
  {
    // Grab a reference to apiAccessor and call methods on it when we need to.
  }
}

Now for your unit tests, you can create a mock object.

class MockWebApiAccessor : IClientSideWebApiAccessor
{
  // Implementation that allows you to control what the methods do,
  // probably by passing delegates into the constructor.
}

You can now test ClientSideWebApiAccessorConsumer by passing in an instance of MockWebApiAccessor which doesn't actually access the web.

I hope that makes sense! Let me know if you'd like any more explanation.

Alex Humphrey
Thank you! But I have another question, I know the way u give, but in this way, I can hardly test the real functionality, e.g. how can i test the OAuth authority api?
Martin Luo
Is OAuth an API you wrote? Or is it someone elses API? If it's someone else's, it's not really yours to test - you just have to assume that it works to spec. What mocking allows you to do is to simulate that API - test how your app handles expected and unexpected responses from it, so that if OAuth ever does give you something you don't expect and violates its spec, you know your app can deal with it.Please let me know if I've understood correctly. I'm really interested in this problem.
Alex Humphrey
@Martin Luo - you've inspired me to write a blog post on this subject - http://alexhumphrey.me.uk/net/mocking-web-service-proxies-using-the-adapter-pattern-to-allow-unit-testing/
Alex Humphrey