单元测试模拟IHttpActionResult GetId方法

本文关键字:方法 GetId IHttpActionResult 模拟 单元测试 | 更新日期: 2023-09-27 18:01:03

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

基本上我有以下内容:-

控制器方法:-

[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");
    }
}

由于某些原因,结果总是为空,因此它没有正确地命中控制器。

你知道为什么会发生这种事吗?调试时,正确的Mock Repository正在访问控制器,并且它应该有3个条目

任何帮助都将不胜感激。

单元测试模拟IHttpActionResult GetId方法

您设置了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");
}