簡體   English   中英

Moq 設置返回 null

[英]Moq setup returns null

所以,我開始在我正在處理的 Web Api 項目上學習實現 UniTesting。 發生的事情是,當我設置一個模擬調用時,這個調用返回 null 而不是我告訴返回的值。 我不知道為什么類似的設置會起作用,但這個設置不起作用。

這是我的測試課

namespace API.Tests.Web
{
    [TestClass]
    public class MaterialsControllerTest
    {
        private MaterialsController controller;
        private Mock<IRTWRepository> repository;
        private Mock<IModelFactory> factory;
        private Mock<IRTWAPIIdentityService> identityService;
        List<MaterialAccepted> materials;
        MaterialAccepted material;      

        [TestInitialize]
        public void Initialize()
        {
            repository = new Mock<IRTWRepository>();
            factory = new Mock<IModelFactory>();          
            identityService = new Mock<IRTWAPIIdentityService>();
            controller = new MaterialsController(repository.Object);
            material = new MaterialAccepted()
            {
                business = true,
                businessService = EnumRecycleCenterService.Dropoff,
                residential = false,
                residentialService = EnumRecycleCenterService.Pickup,
                note = "this a note",
                Category = new Category()
                {
                    name = "Books"
                }
            };

            materials = new List<MaterialAccepted>()
                {
                    new MaterialAccepted() { business=true,businessService=EnumRecycleCenterService.Dropoff,residential=false,residentialService=EnumRecycleCenterService.Pickup,note="this a note"},
                    new MaterialAccepted() { business=false,businessService=EnumRecycleCenterService.Dropoff,residential=true,residentialService=EnumRecycleCenterService.Pickup,note="this a note"},
                };
        }    

        [TestMethod]        
        public void Post_ShouldReturnBadRequestWhenMaterialAcceptedModelValidationFails()
        {            
            //arrange
            repository.Setup(r => r.RecycleCenterRepository.Get(3)).Returns(() => new RecycleCenter());
            controller.ModelState.AddModelError("error", "unit test error");
            //act

            var actionResult = controller.Post(2, new MaterialAcceptedModel());

            Assert.IsInstanceOfType(actionResult, typeof(BadRequestResult));
        }                                        
    }
}

這是我要測試的控制器中的操作

[HttpPost]
        [Route("api/recyclecenters/{rcid}/materials/")]
        public IHttpActionResult Post(int rcid, [FromBody]MaterialAcceptedModel model)
        {
            try
            {
                if (model != null)
                {
                    var recycleCenter = TheRepository.RecycleCenterRepository.Get(rcid);

                    if (recycleCenter == null)
                        return NotFound();

                    if (!ModelState.IsValid)
                        return BadRequest(ModelState);

                    var entity = TheModelFactory.Parse(model);

                    if (entity == null) return BadRequest("Could not read material accepted in body");

                    if (TheRepository.MaterialAcceptedRepository.Get(recycleCenter.RecycleCenterId, entity.Category.name) != null)
                        return Conflict();

                    recycleCenter.Materials.Add(entity);

                    if (TheRepository.SaveAll())
                    {
                        string locationHeader = Url.Link("Materials", new { rcid = rcid, name = model.category.ToLower() });
                        return Created<MaterialAcceptedModel>(locationHeader, TheModelFactory.Create(entity));
                    }
                    return BadRequest("Could not save to the database");
                }
                return BadRequest();
            }
            catch (Exception ex)
            {
                return BadRequest(ex.Message);
            }    
        }

如果我運行此測試,它將失敗,因為它返回的是 NotFoundResult 的實例類型而不是 BadRequestResult,而發生這種情況是因為測試方法在此行中停止

if (recycleCenter == null)
    return NotFound();

但是這個測試它假設停止在這條線上

 if (!ModelState.IsValid)
      return BadRequest(ModelState);

任何想法為什么會這樣

 repository.Setup(r => r.RecycleCenterRepository.Get(3)).Returns(() => new RecycleCenter());

當它應該返回一個新的 RecycleCenter 時返回 null

似乎您正在為 rcid = 3 設置存儲庫模擬,並使用 rcid = 2 在控制器中調用存儲庫。

        //arrange
        repository.Setup(r => r.RecycleCenterRepository.Get(3)).Returns(() => new RecycleCenter());
        controller.ModelState.AddModelError("error", "unit test error");
        //act

        var actionResult = controller.Post(2, new MaterialAcceptedModel());

嘗試使用 rcid = 3 調用它

        var actionResult = controller.Post(3, new MaterialAcceptedModel());

或將 Moq 設置參數更改為It.IsAny<int>()

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM