我有一个正在尝试测试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);
}
}
答案 0 :(得分:0)
您的FluentQuestionAnswerValidator
显然期望IQuestionAnswerRepository
而不是Mock<IQuestionAnswerRepository>
的实例。由于这两者之间没有隐式转换,因此会出现错误。
为此,您实际上想要提供的不是模拟本身,而是由框架创建的实例。因此,请改用此:
_validator = new FluentQuestionAnswerValidator(_qaTest, mockRepo.Object);