예제 #1
0
        public void ByCode_FilterOnly_ItemsWith_EnteredCodes(string validCode1, string validCode2, string invalidCode)
        {
            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.Code).Returns(validCode1);
            ruleForValid1Mock.Setup(s => s.CheckAsync(It.IsAny <FakeModel>()))
            .ReturnsAsync(RuleCheckResult.Success);

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

            ruleForInvalidMock.Setup(s => s.Code).Returns(invalidCode);
            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 result1 = ruleset.ByCode(validCode1).Check(modelMock.Object);
            var result2 = ruleset.ByCode(validCode2).Check(modelMock.Object);
            var result3 = ruleset.ByCode(new[] { validCode1, validCode2 }).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(2));
            ruleForValid2Mock.Verify(v => v.CheckAsync(It.IsAny <FakeModel>()), Times.Exactly(2));
            ruleForInvalidMock.Verify(v => v.CheckAsync(It.IsAny <FakeModel>()), Times.Never());

            Assert.NotNull(result1);
            Assert.NotNull(result2);
            Assert.NotNull(result3);
            Assert.True(result1.IsSuccess);
            Assert.True(result2.IsSuccess);
            Assert.True(result3.IsSuccess);
        }