我正在编写单元测试。为了测试以下方法,

public async Task<Guid> CreateWebJobStatus(string blobId, Guid loggedInUserId, string loggedInUserEmail) {

    Guid webJobStatusId = Guid.NewGuid();

    WebJobStatus newWebJobStatus = new WebJobStatus
    {
        WorkJobStatusId = webJobStatusId,
        TransactionId = Guid.NewGuid(),
        Status = (int)WebJobStatusEnum.PENDING,
        BlobId = blobId,
        UserId = loggedInUserId,
        UserEmail = loggedInUserEmail,
    };
    await _dbContext.WebJobStatus.AddAsync(newWebJobStatus);
    await _dbContext.SaveChangesAsync();

    return webJobStatusId;
}


我嘲笑dbset和dbcontext

public async void CreateWebJobStatusTest() {
    var dbOption = new DbContextOptions<TimeSeriesDbContext>();
    var mockDbContext = new Mock<TimeSeriesDbContext>(dbOption);
    var mockConfig = new Mock<IConfiguration>();
    var instance = new WebJobStatusRepository(mockConfig.Object, mockDbContext.Object);
    var mockValidWebJobId = "11111111-1111-1111-1111-111111111111";
    var webjobStatusList = new List<WebJobStatus>() {
        new WebJobStatus {
            WorkJobStatusId = Guid.Parse(mockValidWebJobId),
            GroupName = "testGroupName",
            Status = 3,
            CreatedDate = DateTimeOffset.UtcNow.AddDays(-10)
        }
    };
    var mockWebJobDbSet = UnitTestUtil.CreateDbSetMock<WebJobStatus>(webjobStatusList.AsQueryable());
    mockDbContext.Setup(x => x.WebJobStatus).Returns(mockWebJobDbSet.Object);

    mockWebJobDbSet.Setup(x => x.AddAsync(It.IsAny<WebJobStatus>(), It.IsAny<System.Threading.CancellationToken>())).Callback((WebJobStatus wj) =>{webjobstatusList.add(wj);});


    var mockuserId = Guid.Parse("22222222-1111-1111-1111-111111111111");

    var result = await instance.CreateWebJobStatus("testBlobId.tsv", mockuserId, "testEmail");
    Assert.IsType<Guid>(result);
    mockDbContext.Verify(x => x.SaveChangesAsync(It.IsAny<System.Threading.CancellationToken>()), Times.Once);
    mockWebJobDbSet.Verify(x => x.AddAsync(It.IsAny<WebJobStatus>(), It.IsAny<System.Threading.CancellationToken>()), Times.Once);
}


除了AddAsync之外,其他所有东西都按预期工作,例外是


  无效的回调。具有参数(WebJobStatus,CancellationToken)的方法上的设置无法调用具有参数(WebJobStatus)的回调。


有人知道吗?

最佳答案

您将需要返回任务以允许异步/等待调用

await _dbContext.WebJobStatus.AddAsync(newWebJobStatus);


流到完成。

因此,假设Add返回添加的对象

mockWebJobDbSet
    .Setup(_ => _.AddAsync(It.IsAny<WebJobStatus>(), It.IsAny<System.Threading.CancellationToken>()))
    .Callback((WebJobStatus model, CancellationToken token) => { webjobstatusList.Add(model); })
    .Returns((WebJobStatus model, CancellationToken token) => Task.FromResult((EntityEntry<WebJobStatus>)null));


请注意,方法Setup需要两个参数,因此CallbackReturns如果要使用捕获的参数,也将需要两个参数。

10-01 21:27