我有一个单元测试需要模拟一个从数据库返回实体属性的方法。我将把我尝试过的一些代码放在这里。如果有人知道如何做,并希望帮助我是受欢迎的。感谢
这是接口,实现接口的类和实体模型:
namespace MoqExample
{
public interface ISomeService
{
Customer GetCustomerById(int customerId);
}
public class SomeService : ISomeService
{
public Customer GetCustomerById(int customerId)
{
// Query database and return Customer;
return Db.Customer.FirstOrDefault(c => c.id == customerId);
}
}
public class Customer
{
public int Id { get; set; }
public string Name { get; set; }
public bool IsActive { get; set; }
}
}
这是我的单元测试:
[TestMethod]
public void TestMyMethod()
{
customer = new Customer();
customer.Id = 1;
customer. Name= "robert"
customer.IsActive = true;
// This works because is mocking a method that return a customer.
this.Setup<ISomeService, Customer>(c => c.GetCustomerById(customerId)).Returns(task);
// This doesn't work because is mocking the same method but here I want to return a property
this.Setup<ISomeService, bool>(c => c.GetCustomerById(customerId).IsActive).Returns(true);
}