日期:2014-05-20 浏览次数:21152 次
public interface IUnitOfWork { int SaveChanges(); } public class UnitOfWork : IUnitOfWork { public int SaveChanges() { return TaskDBContext.SaveChanges(); } } public interface IUserInfoRepository : IRepository<UserInfo> { } public class UserInfoRepository : RepositoryBase<UserInfo>, IUserInfoRepository { public UserInfoRepository(IDatabaseFactory dataBaseFactory) : base(dataBaseFactory) { } } public interface IUserInfoServices { bool UserInfo_Insert(UserInfo userInfo); } public class UserInfoServices : IUserInfoServices { private readonly IUserInfoRepository userInfoRepository; private readonly IUnitOfWork unitOfWork; public UserInfoServices(IUserInfoRepository userinfoRepository, IUnitOfWork unitOfWork) { this.userInfoRepository = userinfoRepository; this.unitOfWork = unitOfWork; } public bool UserInfo_Insert(UserInfo userInfo) { userInfoRepository.Add(userInfo); return unitOfWork.SaveChanges() == 1; } }
public static IUnitOfWork MockUnitOfWork(List<UserInfo> userInfo) { var mockUnitOfWork = new Mock<IUnitOfWork>(); mockUnitOfWork.Setup(x => x.SaveChanges()).Callback<UserInfo>((s) => userInfo.Add(s)); return mockUnitOfWork.Object; } /// <summary> ///UserInfo_Insert 的测试 ///</summary> [TestMethod()] public void UserInfo_InsertTest() { UserInfo userInfo = new UserInfo() { UserId = 1, UserName = "Test", Pwd = "oooooo", Email = "email@email.com" }; List<UserInfo> userInfos = new List<UserInfo>(); int userCount = userInfos.Count; var userInfoRepositoryMock = new Mock<IUserInfoRepository>(); var unitOfWorkMock = MockUnitOfWork(userInfos); var userInfoServicesMock = new Mock<IUserInfoServices>(); var userInfoServices = new UserInfoServices(userInfoRepositoryMock.Object, unitOfWorkMock); userInfoServicesMock.Setup(o => o.UserInfo_Insert(It.IsAny<UserInfo>())).Returns(true); userInfoServices.UserInfo_Insert(userInfo); Assert.AreEqual(userInfos.Count, 2); }
mockUnitOfWork.Setup(x => x.SaveChanges()).Callback<UserInfo>((s) => userInfo.Add(s));