我正在尝试首次为单元测试设置Moq。我已经针对真实数据库测试了工作单元和存储库,我可以插入,删除,按ID查找等等(我正在使用TPH,因为我有住宅客户以及商业客户。)此测试与Moq有效:
const int expectedId = 1;
ResidentialCustomer expected = new ResidentialCustomer("Bob", "Smith")
{
Id = expectedId,
AccountNumber = 1
};
IQueryable<ResidentialCustomer> data = new List<ResidentialCustomer>
{
expected,
new ResidentialCustomer("Nancy", "Smith") {Id = 2, AccountNumber = 2},
new ResidentialCustomer("John", "Doe") {Id = 3, AccountNumber = 3},
new ResidentialCustomer("Jane", "Doe") {Id = 4, AccountNumber = 4}
}.AsQueryable();
var dbSetMock = new Mock<IDbSet<Customer>>();
dbSetMock.Setup(m => m.Provider).Returns(data.Provider);
dbSetMock.Setup(m => m.Expression).Returns(data.Expression);
dbSetMock.Setup(m => m.ElementType).Returns(data.ElementType);
dbSetMock.Setup(m => m.GetEnumerator()).Returns(data.GetEnumerator());
var customDbContextMock = new Mock<RealContext>();
customDbContextMock
.Setup(x => x.Customers)
.Returns(dbSetMock.Object);
var actual = (ResidentialCustomer) customDbContextMock.Object.Customers.First();
Assert.IsNotNull(actual);
Assert.AreEqual(expected.Id, actual.Id);
Assert.AreEqual(expected.FirstName, actual.FirstName);
此测试不(更新):&#39;实际&#39;为null,第一个Assert失败。
const int expectedId = 1;
ResidentialCustomer expected = new ResidentialCustomer("Bob", "Smith")
{
Id = expectedId,
AccountNumber = 1
};
IQueryable<ResidentialCustomer> data = new List<ResidentialCustomer>
{
expected,
new ResidentialCustomer("Nancy", "Smith") {Id = 2, AccountNumber = 2},
new ResidentialCustomer("John", "Doe") {Id = 3, AccountNumber = 3},
new ResidentialCustomer("Jane", "Doe") {Id = 4, AccountNumber = 4}
}.AsQueryable();
var dbSetMock = new Mock<IDbSet<Customer>>();
dbSetMock.Setup(m => m.Provider).Returns(data.Provider);
dbSetMock.Setup(m => m.Expression).Returns(data.Expression);
dbSetMock.Setup(m => m.ElementType).Returns(data.ElementType);
dbSetMock.Setup(m => m.GetEnumerator()).Returns(data.GetEnumerator());
var customDbContextMock = new Mock<RealContext>();
customDbContextMock
.Setup(x => x.Customers)
.Returns(dbSetMock.Object);
var uow = new UnitOfWork(customDbContextMock.Object);
var repo = uow.CustomerRepository;
var actual = (ResidentialCustomer) repo.GetAllCustomers().First();
Assert.IsNotNull(actual);
Assert.AreEqual(expected.Id, actual.Id);
Assert.AreEqual(expected.FirstName, actual.FirstName);
提前谢谢你......