【问题标题】:Unit Testing API Call单元测试 API 调用
【发布时间】:2018-05-19 13:03:17
【问题描述】:

我正在使用 .NET Core 和 xUnit/Moq 来创建单元测试。我想为以下 API 调用创建一个单元测试:

[HttpGet("{zip}")]
public IActionResult Get(int zip)
{
    //debugging here shows the repository has the object
    //but the result is always null
    Location result = repository[zip];
    if(result == null)
    {
        return NotFound();
    }
    else
    {
        return Ok(result);
    }
}

我的单元测试(失败)是:

[Fact]
public void Api_Returns_Json_Object()
{
    //Arrange
    Mock<IRepository> mockRepo = new Mock<IRepository>();
    mockRepo.Setup(m => m.Locations).Returns(new Location[]
    {
        new Location
        {
            zip = 88012,
            type = "STANDARD",
            state = "NM"
        }
    });

    //Arrange
    ApiController controller = new ApiController(mockRepo.Object);

    // Act
    var response = controller.Get(88012);

    // Assert
    Assert.True(response.Equals(HttpStatusCode.OK));
}

当我调试时,存储库显示正确的Location 对象,但结果始终为空,返回NotFound() 状态码。

如果我用 PostMan 测试响应,它可以正常工作。

这里是相关的IRepository 成员:

IEnumerable<Location> Locations { get; }
Location this[int zip] { get; }

【问题讨论】:

    标签: c# unit-testing asp.net-core moq xunit


    【解决方案1】:

    根据被测方法中访问的内容,安排测试时设置了错误的成员

    [Fact]
    public void Api_Returns_Json_Object() {
        //Arrange
        int zip = 88012;
        var location = new Location
        {
            zip = zip,
            type = "STANDARD",
            state = "NM"
        };
    
        Mock<IRepository> mockRepo = new Mock<IRepository>();
        mockRepo.Setup(m => m[zip]).Returns(location);
        var controller = new ApiController(mockRepo.Object);
    
        // Act
        var response = controller.Get(zip);
        var okResult = response as OkObjectResult;
    
        // Assert
        Assert.NotNull(okResult);
        Assert.Equal(location, okResult.Value);
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-11-09
      • 2018-04-27
      • 1970-01-01
      • 2016-06-03
      • 1970-01-01
      • 2016-09-08
      • 2012-03-06
      相关资源
      最近更新 更多