c# - 单元测试 API 调用

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

我将 .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 对象,但结果始终为 null,返回 NotFound() 状态代码。

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

以下是相关的 IRepository 成员:

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

最佳答案

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

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

关于c# - 单元测试 API 调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50425584/

相关文章:

javascript - 有没有办法对不显眼的 jQuery 场景进行单元测试

c# - 单元测试控制台 c# 应用程序的最佳方法

c# - 从 Postman URL 向 API 发送字符串时获取 null

c# - 如何在 .Net Core Web API 中 Swagger 设置基本路径属性

c# - 开发人员的网络安全基础(IIS、SQL、RDP 等)

c# - Silverlight 2 - 使用 WCF 添加数据库记录

python - 如何检查 TDD 中是否存在方法?

Docker 容器监听 http://[::]:80

c# - 使用 C# 验证 SSL 证书

c# - 从类库创建 vsix 包