我正在尝试从基础开始,但无法理解如何创建此moq对象。
public class TestRefMedicalSpecialty
{
private Mock<IRepository<RefMedicalSpecialty>> mockRefMedicalRepo;
public TestRefMedicalSpecialty()
{
var mockRefMedicalSpecialties = new List<RefMedicalSpecialty>
{
new RefMedicalSpecialty {Code = "10000", Description = "Medical Specialty1"},
new RefMedicalSpecialty {Code = "10001", Description = "Medical Specialty2"},
new RefMedicalSpecialty {Code = "10002", Description = "Medical Specialty3"}
};
mockRefMedicalRepo = new Mock<IRepository<RefMedicalSpecialty>>();
mockRefMedicalRepo.Setup(repo => repo.GetAll()).Returns(mockRefMedicalSpecialties);
// this.mockRefMedicalRepo = new Mock<IRepository<RefMedicalSpecialty>>().Object;
this.mockRefMedicalRepo = mockRefMedicalRepo.Object;
}
[Fact]
public void GetAll_Returns_Data()
{
}
}
严重级代码描述项目文件行抑制状态 错误CS0266无法隐式转换类型&#39;
Aamc.Ret.Data.IRepository<Aamc.Ret.Data.Models.RefMedicalSpecialty>
&#39;到&#39;Moq.Mock<Aamc.Ret.Data.IRepository<Aamc.Ret.Data.Models.RefMedicalSpecialty>>
&#39;。存在显式转换(您是否缺少演员?)Aamc.Ret.UnitTests
答案 0 :(得分:3)
Mock<T>.Object
属性返回泛型参数T
的模拟。
因此,在您的情况下,mockRefMedicalRepo.Object
是IRepository<RefMedicalSpecialty>
,但您正尝试将其分配给Mock<IRepository<RefMedicalSpecialty>>
,因为错误消息说明了这一点。
这是一个可能的替代方案
public class TestRefMedicalSpecialty {
private IRepository<RefMedicalSpecialty> mockRefMedicalRepo;
public TestRefMedicalSpecialty() {
var mockRefMedicalSpecialties = new List<RefMedicalSpecialty>
{
new RefMedicalSpecialty {Code = "10000", Description = "Medical Specialty1"},
new RefMedicalSpecialty {Code = "10001", Description = "Medical Specialty2"},
new RefMedicalSpecialty {Code = "10002", Description = "Medical Specialty3"}
};
var mock = new Mock<IRepository<RefMedicalSpecialty>>();
mock.Setup(_ => _.GetAll()).Returns(mockRefMedicalSpecialties);
this.mockRefMedicalRepo = mock.Object;
}
[Fact]
public void GetAll_Returns_Data() {
//pass the mocked repo into a dependent class and
//exercise test that relies on calling GetAll
}
}
参考Moq Quickstart以更好地了解如何使用Moq框架