我正在构建一个测试项目来摆弄.net核心,我正在遇到一些障碍.玩弄的基本思想是将产品添加到上下文中,没有大的权利.错了.因为我是一名优秀的程序员,所以我总是从TDD的方式开始.所以我尝试了以下测试.
[Fact] public async Task AddProduct_ReturnCreatedWithProduct() { Product testProduct = ProductHelpers.GenerateTestProduct(); var mockRepo = new Mock>(); mockRepo.Setup(repo => repo.Get(testProduct.ProductID)).Returns(Task.FromResult(testProduct)); var controller = new ProductController(mockRepo.Object); var result = await controller.Post(new ProductViewModel() { ProductID = 1, ProductShortDesc = PRODUCT_SHORTDESC, ProductDescription = PRODUCT_DESC }); var okResult = Assert.IsType (result); var returnProduct = Assert.IsType (okResult.Value); Assert.Equal(testProduct.ProductShortDesc, returnProduct.ProductShortDesc); Assert.Equal(testProduct.ProductDescription, returnProduct.ProductDescription); } public static Product GenerateTestProduct() { return new Product() { ProductID = 1, ProductShortDesc = "FRI", ProductDescription = "Fristi" }; }
哪个应该回报得体OkObjectResult
.好吧不,不.所以我深深地潜入控制器,给了我这个.
[HttpPost] public async TaskPost([FromBody]ProductViewModel model) { if (!ModelState.IsValid) return BadRequest(ModelState); else { var product = await _productRepository.AddEntity(model.ToEntity()); if (product == null) return StatusCode(500); else return Ok(product); } } public interface IRepository { Task Get (TKey id); IQueryable GetAll(); Task AddEntity(T entity); Task DeleteEntity(T entity); Task Update(T entity); } public class ProductRepository : IRepository { protected readonly DbContext Context; protected DbSet DbSet; public ProductRepository(ApplicationContext context) { Context = context; DbSet = context.Set (); } public async Task AddEntity(Product entity) { try { await Context.Set ().AddAsync(entity); await Save(); return await Get(entity.ProductID); } catch (System.Exception ex) { Debug.WriteLine(ex.Message); throw ex; } } //Rest left out for shortness off this post }
所以通过postman运行代码给了我以下结果:
所以回到测试,因为我想,是的它现在以某种方式工作..
[HttpPost] public async TaskPost([FromBody]ProductViewModel model) { if (!ModelState.IsValid) return BadRequest(ModelState); else { var product = await _productRepository.AddEntity(model.ToEntity()); if (product == null) return StatusCode(500); else return Ok(product); } }
所以这也不顺利.我尝试调试代码以找到根本原因但由于某种原因它不让我在接口代码中单步执行以找出为什么Add不能在我的单元测试中工作,但确实可以在正常的postman测试上工作.(只是我的代码被禁用).希望你们中的一些人可以帮助我解决这个问题