简体   繁体   中英

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

I have a validation class I am trying to test FluentQuestionAnswerValidator , but this class has a dependency IQuestionAnswerRepository which must be passed through the constructor in order to instantiate the validator class.

In order to try and instantiate the class I am using Moq to mock the repository which can then be passed through to the validator.

However I am getting a type error when I attempt to pass in the mocked repository into the validator when instantiating it:

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

How do I change the code I've got so that it will accept the mocked repository as its dependency?

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);
        }
    }

Your FluentQuestionAnswerValidator obviously expects an instance of IQuestionAnswerRepository , not Mock<IQuestionAnswerRepository> . As there is no implicit conversion between those two you get the error.

What you want to provide actually is therefor not the mock itself, but the instance being created by the framework. So use this instead:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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