单元测试部分文本搜索服务

时间:2017-08-15 20:55:55

标签: c# unit-testing xunit

我试图对我拥有的搜索功能进行单元测试,该功能会将部分输入的字符串与结果匹配(如果存在)。 我的测试失败了:

    [Theory(DisplayName = "Retrieve a Customer by partial name if the customer exists.")]
    [InlineData("fifth")]
    public async Task ProviderClass_GetCustomersByPartialName(string name)
    {
        var mockISecurityTokenProvider = new Mock<ISecurityTokenProvider>();
        mockISecurityTokenProvider.Setup(i => i.GetSecurityToken()).Returns(() => new SecurityToken
        {
            CurrentAccessLevel = AccessLevel.Full
        });

        var customerRepository = new CustomerRepository(_context, mockISecurityTokenProvider.Object);
        var irrelevantRepo = new irrelevantRepo(_context, mockISecurityTokenProvider.Object);

        var service = new CustomerProvider(customerRepository, irrelevantRepo,
            new CustomerFactory(), 
            new Mock<IGenericModelFactory<mockedModel, mockedTable>>().Object,
            new Mock<IGenericModelFactory<mockedModel, mockedTable>>().Object,
            new Mock<IGenericModelFactory<mockedModel, mockedTable>>().Object, 
            new Mock<IGenericModelFactory<mockedModel, mockedTable>>().Object,
            new Mock<IGenericModelFactory<mockedModel, mockedTable>>().Object);

        var item = await service.GetCustomersByPartialNameAsync(name);

        Assert.True(item?.Any(i => i.Name.ToLower().Contains(name.ToLower())));

我正在测试的服务代码:

public async Task<IEnumerable<Customer>> GetCustomersByPartialNameAsync(string name,
        CancellationToken cancellationToken = new CancellationToken())
    {
        var items =
            await _customerReader.GetCustomers()
                //Includes of tables where relevant results might be
                .Where(i => i.CustomerStatusId == 1 && i.Name.ToLower().Contains(name.ToLower()))
                .ToListAsync(cancellationToken);

        return items.Select(Create);
    }

我做错了什么?

1 个答案:

答案 0 :(得分:0)

  1. 你应该使用的唯一模拟设置(我看不到)它应该是var data = $.ajax({ dataType: "json", url: 'myjsonurl', data: data });
  2. 请使用customerReader.GetCustomers()default(CancellationToken)
  3. 请在必要时进行模拟,请考虑使用假冒
  4. 希望这个帮助