在webapi中执行Moq时,为什么我的contentResult始终为null

时间:2017-04-17 19:05:54

标签: c# unit-testing asp.net-web-api moq

我试图设置我的Moq进行WebApi单元测试,但Assert.IsNotNull(contentResult)总是失败。那是因为我错误地传递了我的mockList吗?请帮帮我,代码如下

 [TestMethod]
  public void GetCEO()
    {

      // setting up the mock framework
      var mockRepository = new Mock<IUsersRepository>();
      List<Users> mockList = new List<Users>();
      {
          new Users
          {
              User = 1,
              FirstName = "TestFirstName",
              LastName = "TestLastName",
              Group = "CEO"
          };
      }
      mockRepository
     .Setup(x => x.GetCEOs())
     .Returns(mockList);

     var controller = new UsersController(mockRepository.Object);

     IHttpActionResult actionResult = controller.Get();
     var contentResult = actionResult as OkNegotiatedContentResult<IEnumerable<Users>>;
     Assert.IsNotNull(mockList);
     Assert.IsNotNull(contentResult);
     Assert.IsNotNull(contentResult.Content);
     var users = contentResult.Content;
     Assert.AreEqual(1, users.Count());

}

请检查我的获取行动方法

 [HttpGet]
    [Route("api/GetCEO")]
    public IHttpActionResult Get()
    {
        var data=_repository.GetCEOs();
        if (data == null)
            return NotFound();
        else
        return Ok(data);

    }

My IusersRepositoy

    public interface IUsersRepository
{
    List<Users> GetUsers(int supervisor);

    List<Users> GetCEOs();
}

1 个答案:

答案 0 :(得分:2)

导致as投射失败并导致null

actionResult as OkNegotiatedContentResult<IEnumerable<Users>>

有问题。根据您的编辑,您的方法定义在

之下
List<Users> GetCEOs();

你应该转为

actionResult as OkNegotiatedContentResult<List<Users>>

是的,因为你的代码充满了错误。它应该像下面的

  List<Users> mockList = new List<Users>()
  {
      new Users
      {
          User = 1,
          FirstName = "TestFirstName",
          LastName = "TestLastName",
          Group = "CEO"
      }
  };

  mockRepository
 .Setup(x => x.GetCEOs())
 .Returns(mockList);