使用moq设置一个方法来返回一个对象列表但是变为null

时间:2016-07-19 17:36:01

标签: c# unit-testing async-await moq

我已经在我的个人项目中进行了测试并遇到了这个小问题。我有一个创建对象列表的测试方法,我设置了我在我测试的方法中使用的服务,以返回模拟列表。但是,由于某种原因,设置无法正常工作,并且返回null。

以下是测试方法:

var mockList = new List<IBillItem>
{
    new BillItem
    {
        Id = 0,
        DueDate = new DateTime(),
        Name = "",
        IndexNumber = "",
        AccountNumber = "",
        Amount = decimal.One
    },
    new BillItem
    {
        Id = 0,
        DueDate = new DateTime(),
        Name = "",
        IndexNumber = "",
        AccountNumber = "",
        Amount = decimal.One
    }
};

_billHandlingService.Setup(x => x.GetAllBillsAsync(It.IsAny<string>())).Returns(Task.FromResult(mockList));

var listBillsVm = new ListBillsViewModel(new LoggerFactory(), _billHandlingService.Object, _settingsService.Object);

await listBillsVm.GetBillsAsync();

_billHandlingService.Verify(x => x.GetAllBillsAsync(_settingsService.Name), Times.AtMostOnce);

Assert.AreEqual(1, listBillsVm.BillsList.Count);

以下是具体类im测试的代码:

public async Task GetBillsAsync()
{
    BillsList.Clear();

    var bills = await _billHandlingService.GetAllBillsAsync(_settingsService.LoggerUser);

    if (null != bills)
    {
        var billsByDate = bills.Where(x => x.DueDate == DateTime.Today).ToList();
        foreach (var bill in billsByDate)
        {
            BillsList.Add(bill);
            RaisePropertyChanged(nameof(BillsList));
        }
    }
}

我尝试搜索SO / google的搜索结果尚未找到任何答案。提前谢谢。

编辑:代码没有评论,但我认为它足够清楚,请在评论中询问是否有需要清算的内容

编辑2:

Task<List<IBillItem>>GetAllBillsAsync(string username); 

是否调用该方法的接口。

2 个答案:

答案 0 :(得分:2)

您可以尝试将.Returns中的Setup更改为.ReturnsAsync(mockList)

//...other code removed for brevity
_billHandlingService
    .Setup(x => x.GetAllBillsAsync(It.IsAny<string>()))
    .ReturnsAsync(mockList);
//...other code removed for brevity

<强>更新

根据您的问题使用以下最小完整可验证示例来尝试重现您的问题。请注意,我省略了创建测试所不需要的任何类。

class ListBillsViewModel {
    private IBillHandlingService _billHandlingService;
    private ISettingsService _settingsService;

    public ListBillsViewModel(IBillHandlingService billHandlingService, ISettingsService settingsService) {
        this._billHandlingService = billHandlingService;
        this._settingsService = settingsService;
        BillsList = new List<IBillItem>();
    }

    public List<IBillItem> BillsList { get; set; }

    public async Task GetBillsAsync() {
        BillsList.Clear();

        var bills = await _billHandlingService.GetAllBillsAsync(_settingsService.LoggerUserName);

        if (null != bills) {
            var billsByDate = bills.Where(x => x.DueDate == DateTime.Today).ToList();
            foreach (var bill in billsByDate) {
                BillsList.Add(bill);
            }
        }
    }
}

public interface ISettingsService {
    string Name { get; }
    string LoggerUserName { get; set; }
}

public interface IBillHandlingService {
    Task<List<IBillItem>> GetAllBillsAsync(string username);
}

public class BillItem : IBillItem {
    public int Id { get; set; }
    public DateTime DueDate { get; set; }
    public string Name { get; set; }
    public string IndexNumber { get; set; }
    public string AccountNumber { get; set; }
    public decimal Amount { get; set; }
}

public interface IBillItem {
    int Id { get; set; }
    DateTime DueDate { get; set; }
    string Name { get; set; }
    string IndexNumber { get; set; }
    string AccountNumber { get; set; }
    decimal Amount { get; set; }
}

然后根据上述类

重建以下单元测试
[TestMethod]
public async Task Moq_Setup_Should_Return_List_Of_Objects() {
    var mockList = new List<IBillItem>
    {
        new BillItem
        {
            Id = 0,
            DueDate = DateTime.Today,
            Name = "User",
            IndexNumber = "",
            AccountNumber = "",
            Amount = decimal.One
        },
        new BillItem
        {
            Id = 1,
            DueDate = DateTime.Today.AddDays(1),
            Name = "User",
            IndexNumber = "",
            AccountNumber = "",
            Amount = decimal.One
        }
    };

    string name = "User";

    var _settingsService = new Mock<ISettingsService>();
    _settingsService
        .Setup(m => m.Name)
        .Returns(name);
    _settingsService
        .Setup(m => m.LoggerUserName)
        .Returns(name);

    var _billHandlingService = new Mock<IBillHandlingService>();
    _billHandlingService
        .Setup(x => x.GetAllBillsAsync(It.IsAny<string>()))
        .ReturnsAsync(mockList);

    var listBillsVm = new ListBillsViewModel(_billHandlingService.Object, _settingsService.Object);

    await listBillsVm.GetBillsAsync();

    _billHandlingService.Verify(x => x.GetAllBillsAsync(_settingsService.Name), Times.AtMostOnce);

    Assert.AreEqual(1, listBillsVm.BillsList.Count);
}

我运行了上述测试,它按预期通过了.Returns(Task.FromResult(mockist)).ReturnsAsync(mockList)的两个设置。

您提供的示例与您的实际情况不符,或者问题超出了您在帖子中描述的内容。

答案 1 :(得分:0)

您需要在List<IBillItem>上指定Task.FromResult,如下所示:

_billHandlingService.Setup<Task<List<IBillItem>>>(
    x => x.GetAllBillsAsync(It.IsAny<string>()))
                    .Returns(Task.FromResult<List<IBillItem>>(mockList));

类似的SO Q和A here