我试图设置我的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();
}
答案 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);