예제 #1
0
        public void ByCategory_FilterOnly_ItemsFrom_TheGivenCategory(string validCategory, string invalidCategory)
        {
            var modelMock           = new Mock <FakeModel>();
            var serviceProviderMock = new Mock <IServiceProvider>();
            var ruleForValid1Mock   = new Mock <IRuleFor <FakeModel> >();
            var ruleForValid2Mock   = new Mock <IRuleFor <FakeModel> >();
            var ruleForInvalidMock  = new Mock <IRuleFor <FakeModel> >();

            ruleForValid1Mock.Setup(s => s.Category).Returns(validCategory);
            ruleForValid1Mock.Setup(s => s.CheckAsync(It.IsAny <FakeModel>()))
            .ReturnsAsync(RuleCheckResult.Success);

            ruleForValid2Mock.Setup(s => s.Category).Returns(validCategory);
            ruleForValid2Mock.Setup(s => s.CheckAsync(It.IsAny <FakeModel>()))
            .ReturnsAsync(RuleCheckResult.Success);

            ruleForInvalidMock.Setup(s => s.Category).Returns(invalidCategory);
            ruleForInvalidMock.Setup(s => s.CheckAsync(It.IsAny <FakeModel>()))
            .ReturnsAsync(RuleCheckResult.Fail);

            serviceProviderMock
            .Setup(p => p.GetService(typeof(IEnumerable <IRuleFor <FakeModel> >)))
            .Returns(new List <IRuleFor <FakeModel> >(new[]
            {
                ruleForValid1Mock.Object,
                ruleForValid2Mock.Object,
                ruleForInvalidMock.Object
            }));

            var ruleset = new RuleSet <FakeModel>(serviceProviderMock.Object);
            var result  = ruleset.ByCategory(validCategory).Check(modelMock.Object);

            serviceProviderMock.Verify(
                v => v.GetService(typeof(IEnumerable <IRuleFor <FakeModel> >)),
                Times.Exactly(1));

            ruleForValid1Mock.Verify(v => v.CheckAsync(It.IsAny <FakeModel>()), Times.Exactly(1));
            ruleForValid2Mock.Verify(v => v.CheckAsync(It.IsAny <FakeModel>()), Times.Exactly(1));
            ruleForInvalidMock.Verify(v => v.CheckAsync(It.IsAny <FakeModel>()), Times.Never());

            Assert.NotNull(result);
            Assert.True(result.IsSuccess);
        }