如何单元测试Web API调用方法

InT*_*ons 0 unit-testing asp.net-mvc-4

我在我的Repository层中调用Web Api方法.任何人都可以建议如何使用Mocking进行测试

Dar*_*rov 7

如果要模拟对Web API方法的调用,则必须抽象调用它的代码.

如此抽象:

public interface IMyApi
{
    MyObject Get();
}
Run Code Online (Sandbox Code Playgroud)

然后你可以使用HttpClient调用实际API的这个接口的特定实现:

public class MyApiHttp: IMyApi
{
    private readonly string baseApiUrl;
    public MyApiHttp(string baseApiUrl)
    {
        this.baseApiUrl = baseApiUrl;
    }

    public MyObject Get()
    {
        using (var client = new HttpClient())
        {
            client.BaseAddress = this.baseAddress;
            var response = client.GetAsync('/api/myobjects').Result; 
            return response.Content.ReadAsAsync<MyObject>().Result;
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

现在,您的存储库层将简单地将此抽象作为构造函数参数:

public class Repository: IRepository
{
    private readonly IMyApi myApi;
    public Repository(IMyApi myApi)
    {
        this.myApi = myApi;
    }

    public void SomeMethodThatYouWantToTest()
    {
        var result = this.myApi.Get();
        ...
    }
}
Run Code Online (Sandbox Code Playgroud)

接下来在您的单元测试中,使用您喜欢的模拟框架模拟对API的访问是微不足道的.例如,使用NSubstitute的单元测试可能如下所示:

// arrange
var myApiMock = Substitute.For<IMyApi>();
var sut = new Repository(myApiMock);
var myObject = new MyObject { Foo = "bar", Bar = "baz" };
myApiMock.Get().Returns(myObject);

// act
sut.SomeMethodThatYouWantToTest();

// assert
...
Run Code Online (Sandbox Code Playgroud)