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!
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.