I will like to write a xunit test for the controller method below
[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();
}
}
My viewmodel looks like this.
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; }
}
Here is what my repository looks like.
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;
}
I started getting this error message
cannot convert from 'System.Collections.Generic.List<CoreServices.ViewModel.PostViewModel>'
to 'System.Threading.Tasks.Task<System.Collections.Generic.List<CoreServices.ViewModel.PostViewModel>>'
Here is what my xunit test looks like.
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()
}
}
I will like to complete my first test which will show the count of the post is 2 (mocking a dependency). How can I write this/complete this test ?