单元测试模拟IHttpActionResult GetId方法

时间:2016-08-06 13:57:05

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

我正在为控制器创建一些单元测试但是我遇到了问题。

基本上我有以下内容: -

控制器方法: -

[ResponseType(typeof(Attrib))]
public IHttpActionResult GetAttrib(int id)
{
    var attrib = _attribsRepository.GetAttrib(id);
    if (attrib == null)
    {
        return NotFound();
    }

    return Ok(attrib);
}

它是一个简单的Web API 2.0方法。

然后我有了存储库: -

public Attrib GetAttrib(int id)
{
    return DbSet.FirstOrDefault(x=>x.Id == id);
}

最后测试方法: -

public class AttribsControllerTests
{
    public Mock<IAttribsRepository> _attribsRepositoryMock;
    public List<Attrib> AttribList;
    public AttribsController AttribsController;
    [SetUp]
    public void Init()
    {
        _attribsRepositoryMock = new Mock<IAttribsRepository>();
        AttribList = new List<Attrib>
        {
            new Attrib()
            {
                Id = 1,
                AttributeId = "Cro",
                AttributeName = "Crossing",
                AttributeType = "Tech",
                AttributeValue = 1
            },
            new Attrib()
            {
                Id = 2,
                AttributeId = "Dri",
                AttributeName = "Dribbling",
                AttributeType = "Tech",
                AttributeValue = 2
            },
            new Attrib()
            {
                Id = 3,
                AttributeId = "Fin",
                AttributeName = "Finishing",
                AttributeType = "Tech",
                AttributeValue = 3
            }
        };
    }

    [Test]
    public void Get_Check_That_Id1_Returns_Crossing()
    {
        //Arrange
        _attribsRepositoryMock.Setup(t => t.GetStaticAttribs()).Returns(AttribList.AsQueryable());

        //Act
        var attribsController = new AttribsController(_attribsRepositoryMock.Object);

        var result = attribsController.GetAttrib(1) as OkNegotiatedContentResult<Attrib>;

        //Assert
        Assert.IsNotNull(result);
        Assert.AreEqual(AttribList[0].AttributeName, "Cor");
    }
}

由于某种原因,结果始终为null,因此它没有正确地击中控制器。

为什么会发生这种情况的任何想法?在调试时,正确的Mock Repository会命中控制器,它应该包含3个条目。

非常感谢任何帮助。

1 个答案:

答案 0 :(得分:1)

您设置了GetStaticAttribs但在您展示的示例中没有使用它。你想设置IAttribsRepository.GetAttrib

基于您的示例

[Test]
public void Get_Check_That_Id1_Returns_Crossing() {
    //Arrange
    var id = 1;
    _attribsRepositoryMock.Setup(t => t.GetAttrib(id)).Returns(AttribList[0]);
    var attribsController = new AttribsController(_attribsRepositoryMock.Object);

    //Act
    var result = attribsController.GetAttrib(id) as OkNegotiatedContentResult<Attrib>;

    //Assert
    Assert.IsNotNull(result);
    Assert.IsNotNull(result.Content);
    Assert.AreEqual(result.Content.AttributeName, "Crossing");
}