我试图找出一种方法来创建实现存储库接口的 MockRepository。目前,这就是我所拥有的:
public class MockUserRepository
{
private readonly IList<User> _users;
public MockUserRepository()
{
_users = new List<User>()
{
new User()
{
UserId = new Guid("E480E40F-6802-4296-B2A8-E0D5E018CD41"),
Username = "admin",
Password = "5A105E8B9D40E1329780D62EA2265D8A",
CellPhone = "3175172957"
}
};
}
public IUserRepository Create()
{
var mockUserRepository = new Mock<IUserRepository>();
mockUserRepository.Setup(m => m.Count()).Returns(_users.Count());
mockUserRepository.Setup(m => m.Get()).Returns(_users);
mockUserRepository.Setup(m => m.Get(It.IsAny<Guid>())).Returns((Guid id) => _users.First(x => x.UserId == id));
mockUserRepository.Setup(m => m.Save(It.IsAny<User>())).Returns(
(User user) =>
{
var now = DateTime.Now;
user.ModifiedOn = now;
if(user.UserId.Equals(Guid.Empty))
{
user.CreatedOn = now;
_users.Add(user);
}
else
{
var original = _users.First(x => x.UserId == user.UserId);
if (original == null)
{
return false;
}
original = user;
}
return true;
}
);
mockUserRepository.Setup(m => m.Find(It.IsAny<IList<object[]>>())).Returns(
(IList<object[]> criteria) =>
{
IList<User> uList = _users.ToList();
foreach (object[] criteriaItem in criteria)
{
var name = (string)criteriaItem[0];
var value = (string)criteriaItem[1];
IList<User> tempList = uList.ToList();
IList<User> addList = tempList.Where(user => (string) user.GetType().GetProperty(name).GetValue(user, null) == value).ToList();
uList = addList;
}
return uList;
});
return mockUserRepository.Object;
}
}
我想要这样的东西:
public class MockUserRepository : IUserRepository
然后,让我所有的模拟方法实际实现。我想这样做是为了强制我的开发人员完全模拟基于接口的存储库。
从测试方面来看,这个 Mocked Repository 是这样使用的:
[SetUp]
public void Setup()
{
MockUserRepository = new MockUserRepository().Create();
MockRoleRepository = new MockRoleRepository().Create();
MockQuestionRepository = new MockQuestionRepository().Create();
AuthenticationService = new AuthenticationService(MockUserRepository, MockRoleRepository, MockQuestionRepository);
}
所有这些工作都很好,但我真的坚持强制我的 MockRepository 实现它的所有接口方法。