繁体   English   中英

使用Moq模拟要测试的对象的依赖关系时出现类型错误

[英]Type error when using Moq to mock dependency for object being tested

我有一个验证类,我正在尝试测试FluentQuestionAnswerValidator ,但是此类具有依赖项IQuestionAnswerRepository ,必须将其通过构造函数传递才能实例化验证器类。

为了尝试实例化该类,我使用Moq来模拟存储库,然后可以将其传递给验证器。

但是,当我尝试在实例化实例库时将模拟的存储库传递到验证器时,出现类型错误:

Error   CS1503  Argument 2: cannot convert from 
'Moq.Mock<IQuestionAnswerRepository>' to 'IQuestionAnswerRepository'    

如何更改已有的代码,以使其接受模拟的存储库作为其依赖项?

class QuestionAnswerValidationTest
    {
        private QuestionAnswer _qaTest;
        private FluentQuestionAnswerValidator _validator;
        private Mock<IQuestionAnswerRepository> mockRepo;

        [SetUp]
        public void Setup()
        {
            _qaTest = new QuestionAnswer()
            {
                Id = 2,
                Type = "Number",
                Required = true,
                QuestionSection = 1,
            };

            QuestionAnswer qa = new QuestionAnswer()
            {
                Id = 1,
                Type = "String",
                Required = true,
                QuestionSection = 1,
                Answer = "Yes",
                ConditionalQuestionId = null,
                ConditionalQuestionAnswered = null
            };

            Dictionary<int, QuestionAnswer> questionMap = new Dictionary<int, QuestionAnswer>();
            questionMap.Add(qa.Id, qa);

            mockRepo = new Mock<IQuestionAnswerRepository>(MockBehavior.Strict);
            mockRepo.Setup(p => p.QuestionMap).Returns(questionMap);
        }

        [Test]
        public void Validate_AnswerDoesNotMatchQuestionType_ProducesValidationError()
        {
            _qaTest.Answer = "string";

            _validator = new FluentQuestionAnswerValidator(_qaTest, mockRepo);
        }
    }

您的FluentQuestionAnswerValidator显然希望使用IQuestionAnswerRepository实例,而不是Mock<IQuestionAnswerRepository>实例。 由于这两者之间没有隐式转换,因此会出现错误。

因此,您实际上想要提供的不是模拟本身,而是由框架创建的实例 所以改用这个:

_validator = new FluentQuestionAnswerValidator(_qaTest, mockRepo.Object);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM