如何在xunit中使用moq测试异步Task <iactionresult>返回IEnumerable <model>?

时间:2019-01-02 13:48:43

标签: c# moq xunit asp.net-core-webapi-2.1

我想测试我的Controller的GetMoviesAsync。我不知道我的起订量设置在哪里做错了。我从GetMoviesAsync得到0个项目。

请让我我做错了。同时提供正确的解决方案。

// Api控制器:

   public interface ICommand
   {
        Task<IEnumerable<Movie>> GetMoviesAsync();
   }

   public class SampleController : ControllerBase
    {
        private readonly ICommand movieCommand;

        public SampleController(ICommand command)
        {
            movieCommand = command;
        }

        [HttpGet]
        public async Task<IActionResult> GetMoviesAsync()
        {
            var movies = await movieCommand.GetMoviesAsync();
            return Ok(movies);
        }
    }

//单元测试:

public class SampleControllerTest
    {
        private IEnumerable<Movie> MovieList()
        {
            IList<Movie> movies = new List<Movie>()
            {
                new Movie()
                {
                    ID =1,
                    Title = "Test",
                    ReleaseDate = DateTime.Now,
                    RunningTimeInMinutes = 100
                }
            };
            return movies;
        }

        private SampleController GetSampleController()
        {
            var command = new Mock<ICommand>();

            return new SampleController(command.Object);
        }

        [Fact]
        public async Task GetMovies_Test()
        {
            // Arrange
            var controller = GetSampleController();
            var commadMock = new Mock<ICommand>();
            // How to setup moq here?
            commadMock.Setup(s => s.GetMoviesAsync()).Returns(Task.FromResult<IEnumerable<Movie>>(MovieList())).Verifiable();
            // Act
            var response = await controller.GetMoviesAsync() as OkObjectResult;
            // Problem is here, 
            var li=response.Value as IEnumerable<Movie>;
         }
    }

2 个答案:

答案 0 :(得分:1)

  

请告诉我我做错了什么。

正在使用两个完全不同的模拟。

一个用于创建控制器

private SampleController GetSampleController()
{
    var command = new Mock<ICommand>();

    return new SampleController(command.Object);
}

,另一个正在创建并在测试中设置。

var controller = GetSampleController();
var commadMock = new Mock<ICommand>();
// How to setup moq here?
commadMock.Setup(s => s.GetMoviesAsync()).Returns(Task.FromResult<IEnumerable<Movie>>(MovieList())).Verifiable();
  

也提供正确的解决方案。

使用相同的模拟物获得所需的行为

[Fact]
public async Task GetMovies_Test() {
    // Arrange
    var commadMock = new Mock<ICommand>();
    var controller = new SampleController(commadMock.Object); //<---
    commadMock
        .Setup(_ => _.GetMoviesAsync())
        .ReturnsAsync(MovieList())
        .Verifiable();

    // Act
    var response = await controller.GetMoviesAsync() as OkObjectResult;

    //Assert
    var list = response.Value as IEnumerable<Movie>;

    //...
 }

请注意使用ReturnsAsync来设置返回的Task

答案 1 :(得分:0)

似乎您未在Controller上使用正确的模拟。您正在使用的方法在GetMoviesAsync方法顶部没有任何设置