为asp.net核心网络api中的方法编写测试[重复]

问题描述 投票:0回答:2

我想为下面的控制器方法编写一个xunit测试

        [HttpGet]
        [Route("GetPosts")]
        public async Task<IActionResult> GetPosts()
        {
            try
            {
                var posts = await postRepository.GetPosts();
                if (posts == null)
                {
                    return NotFound();
                }

                return Ok(posts);
            }
            catch (Exception)
            {
                return BadRequest();
            }
        }

我的视图模型看起来像这样。

        public class PostViewModel
            {
                public int PostId { get; set; }
                public string Title { get; set; }
                public string Description { get; set; }
                public int? CategoryId { get; set; }
                public DateTime? CreatedDate { get; set; }
                public string CategoryName { get; set; }
            }

这是我的存储库的外观。

        public async Task<List<PostViewModel>> GetPosts()
                {
                    if (db != null)
                    {
                        return await (from p in db.Post
                                      from c in db.Category
                                      where p.CategoryId == c.Id
                                      select new PostViewModel
                                      {
                                          PostId = p.PostId,
                                          Title = p.Title,
                                          Description = p.Description,
                                          CategoryId = p.CategoryId,
                                          CategoryName = c.Name,
                                          CreatedDate = p.CreatedDate
                                      }).ToListAsync();
                    }

                    return null;
        }

我开始收到此错误消息

        cannot convert from 'System.Collections.Generic.List<CoreServices.ViewModel.PostViewModel>' 
        to 'System.Threading.Tasks.Task<System.Collections.Generic.List<CoreServices.ViewModel.PostViewModel>>' 

这是我的xunit测试的样子。

        public class PostControllerTest
        {
            private readonly Mock<IPostRepository> _mockRepo;
            private readonly PostController  _controller;

            public PostControllerTest()
            {
                _mockRepo = new Mock<IPostRepository>();
                _controller = new PostController(_mockRepo.Object);
            }

            [Fact]
            public void GetPosts_TaskExecutes_ReturnsExactNumberOfPosts()
            {
                _mockRepo.Setup(repo => repo.GetPosts())
                    .Returns(new List<PostViewModel>() { new PostViewModel(), new PostViewModel() });

                    //var result = 
                    //Assert.True()
            }
        }

我想完成我的第一个测试,该测试将显示该帖子的计数为2(模拟一个依赖项)。我该如何编写/完成此测试?

c# asp.net-core xunit
2个回答
0
投票
© www.soinside.com 2019 - 2024. All rights reserved.