我正在使用Moq对我们使用Entity Framework的一些代码进行单元测试.在我的单元测试中,我有以下代码,但是当我测试它时,我无法获得正确的返回值(一切编译好,但计数结果为0,返回null).这告诉我,我的Entity对象从未添加到我的模拟仓库中.
[TestMethod] public void GetEntity_ValidName_EntityReturned() { Entity testEntity = new Entity(); testEntity.Name = "Test"; var mockService = new Mock(); mockService.Setup(mock => mock.EntityRepo.Add(testEntity)); IUnitOfWork testDB = mockService.Object; testDB.EntityRepo.Add(testEntity); Entity testEntity2 = EntityHelper.getEntity(testDB,testEntity.Name); int count = testDB.EntityRepo.Count(); Assert.AreEqual(testEntity.Name,testEntity2.Name); }
如何添加实体?我还需要吗?我也尝试了以下无法编译:
mockService.Setup(mock => mock.EntityRepo.Add(testEntity)).Returns(testEntity);
同上:
mockService.SetupGet(mock => mock.EntityRepo.Add(testEntity)).Returns(testEntity);
编辑:这是测试的目标:
public static Entity getEntity(IUnitOfWork database, string entityName) { Entity _entity = database.EntityRepo.Find(x => x.Name.ToLower().Trim() == entityName).FirstOrDefault(); return _entity; }
NikolaiDante.. 5
这是您需要模拟的命令:
database.EntityRepo.Find
你不必担心嘲笑服务,只需要IUnitOfWork
像:
testDB.Setup(m => m.Find(It.IsAny
工作示例:
由于双点睛的,我们需要挂一个模拟断IUnitOfWork
供EntityRepo
[TestMethod] public void GetEntity_ValidName_EntityReturned() { Entity testEntity = new Entity(); testEntity.Name = "Test"; var mockEntityRepo = new Mock(); // Type of Repo here var mockService = new Mock (); mockService.Setup(m => m.EntityRepo).Returns(mockEntityRepo.Object); mockEntityRepo.Setup(m => m.Find(It.IsAny >>())).Returns(testEntity); Entity testEntity2 = EntityHelper.getEntity(mockService.Object, testEntity.Name); int count = testDB.EntityRepo.Count(); Assert.AreEqual(testEntity.Name,testEntity2.Name); }
模拟设置应该对应于被测试方法中的调用.
这是您需要模拟的命令:
database.EntityRepo.Find
你不必担心嘲笑服务,只需要IUnitOfWork
像:
testDB.Setup(m => m.Find(It.IsAny
工作示例:
由于双点睛的,我们需要挂一个模拟断IUnitOfWork
供EntityRepo
[TestMethod] public void GetEntity_ValidName_EntityReturned() { Entity testEntity = new Entity(); testEntity.Name = "Test"; var mockEntityRepo = new Mock(); // Type of Repo here var mockService = new Mock (); mockService.Setup(m => m.EntityRepo).Returns(mockEntityRepo.Object); mockEntityRepo.Setup(m => m.Find(It.IsAny >>())).Returns(testEntity); Entity testEntity2 = EntityHelper.getEntity(mockService.Object, testEntity.Name); int count = testDB.EntityRepo.Count(); Assert.AreEqual(testEntity.Name,testEntity2.Name); }
模拟设置应该对应于被测试方法中的调用.