如何使用FakeItEasy在WebApi控制器上执行集成测试?

时间:2018-05-17 10:17:28

标签: unit-testing asp.net-web-api nunit integration-testing fakeiteasy

我是实施单元测试和集成测试的新手。我正在尝试为我的应用程序编写一些集成测试。 以下是我的应用程序中的代码片段,让您了解我的代码。 如果你能为我提供一些指导,那将是很有帮助的。

public async Task<List<Customer>> HandleAsync(GetCustomerRequest request)
{
    var result = await customerService.GetCustomer(request.CustomerNumber, request.CustomerType);
    // some business logic 
    return result;
}

以下是GetCustomerRequest处理程序的实现

public async Task<List<Customer>> GetCustomer(string customerNumber, string customerType = null)
{

    using (var dataContext = _dataContextFactory.Invoke())
    {
        result = await dataContext.Customers
            .Where(b => b.CustomerNumber == customerNumber)
            .Where(b => b.CustomerType == customerType)
            .Select(b => new Customer
            {
                // Properties assignment...
            })
            .ToListAsync();
    }

    return result;
}

以下是customerService的实施

namespace MyApplication.Tests.Integrations
{
    [TestFixture]
    public class CustomersControllerTests
    {
        private string _baseAddress;
        private string _username;
        private string _password;
        private IApiClient _apiClient;

        [SetUp]
        public void Setup()
        {
            _baseAddress = "https://mywebaaplication.com"; // TODO get this from a config
            _username = "";
            _password = "";
            _apiClient = new ApiClient(new ApiClientAuthenticationHandler(), _baseAddress);  // REPLACE with AzureADApiClientAuthenticationHandler
        }

        [Test]
        public async Task CustomersController_GetCustomer()
        {
            var customerNumber = string.Empty;
            var customerType = 500;
            var result = await _apiClient.GetAsync<Customer[]>($"/api/customers/GetCustomer?customerNumber={customerNumber}&customerType={customerType}");
            Assert.IsNotNull(result);
            Assert.IsTrue(result?.Length > 0);
        }
    }
}

以下是我尝试过的集成单元测试。

{{1}}

1 个答案:

答案 0 :(得分:0)

您可以做一些事情:

  1. 在单元测试中创建一个虚拟主机,然后对其进行http请求
  2. 不是在单元测试中测试您的控制器,而是在活动性/就绪性检查中测试(因为无论如何它只是粘合代码)。只需为您的服务进行集成测试。
  3. 只需测试“新的CustomerController”

这里没有正确/错误的答案。您只需查看风险,然后进行相应的测试。还取决于您期望的代码更改的类型。有时仅在新更改的上下文中创建测试就可以了,无需预料所有事情。