我想为下面的控制器方法编写一个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(模拟依赖项)。 我该如何编写/完成此测试?
答案 0 :(得分:0)
除了您的退货价值设置外,我认为其他一切都很好。您需要返回一个任务。试试这个
_mockRepo.Setup(repo => repo.GetPosts())
.Returns(Task.FromResult(new List<PostViewModel>() { new PostViewModel(), new PostViewModel() }));
答案 1 :(得分:0)
尝试使用ReturnsAsync
代替Returns
。 GetPosts
是异步方法。