不使用moq + autofaq调用回调

时间:2015-08-25 16:33:15

标签: c# unit-testing moq autofac

我使用moq进行单元测试来模拟对象,测试工作正常,现在我想使用autofac + moq,但我遇到了一些问题。   这是测试:

using (var mock = AutoMock.GetLoose())
{

    var issues = new List<Issue>();
    issues.Add(new Issue { Organization = "org", Repository = "repo", Number = 1 });
    issues.Add(new Issue { Organization = "org", Repository = "repo", Number = 2 });
    var numKeys = 0;

    mock.MockRepository.Create<IStorageService>()
        .Setup(myMock => myMock.GetBatchIssues(It.IsAny<string>(), 
                                               It.IsAny<string>(), 
                                               It.IsAny<IList<string>>()))
        .Callback((string org, string repo, IList<string> keys) => numKeys = keys.Count)
        .Returns(issues);

    var sut = mock.Create<IssueReceiveService>();

    var check = await sut.CheckInStorage("org", "repo", issues);
    Assert.AreEqual(issues.Count, numKeys);
}

对sut.CheckInStorage的调用返回null,并且变量numKeys未更新为正确的值。这个测试只使用moxk工作正常,所以我想我错过了如何使用autoMock配置模拟。 我在哪里可以找到更多信息?

更新

经过几次测试后,我找到了解决方案

       using (var mock = AutoMock.GetLoose())
        {
            var issues = new List<Issue>();
            issues.Add(new Issue { Organization = "org", Repository = "repo", Number = 1 });
            issues.Add(new Issue { Organization = "org", Repository = "repo", Number = 2 });
            var numKeys = 0;

            mock.Mock<IStorageService>()
                .Setup(myMock => myMock.GetBatchIssues(It.IsAny<string>(), It.IsAny<string>(), It.IsAny<IList<string>>()))
                .Callback((string org, string repo, IList<string> keys) => numKeys = keys.Count)
                .Returns(issues);

            var sut = mock.Create<IssueReceiveService>();

            var check = await sut.CheckInStorage("org", "repo", issues);
            Assert.AreEqual(issues.Count, numKeys);
        }

0 个答案:

没有答案