模拟接口ReturnsAsync返回null

时间:2017-11-07 17:01:22

标签: c# unit-testing moq

我正在尝试使用Mock方法的Interface Task<string>

这里的问题相同,但我似乎无法让代码对我有利:Setup async Task callback in Moq Framework

我的界面如下所示:

public interface IHttpClient
{
    Task<string> GetStringAsync(string uri);
}

我试图嘲笑这个:

var mockHttp = new Mock<IHttpClient>();
mockHttp.Setup(m => m.GetStringAsync("aPretendUrl")).ReturnsAsync("Some sort of string");

我发现GetStringAsync的结果是null

在注入此实例的控制器中,我将其称为:

string responseData = await _client.GetStringAsync(url);

也在尝试

string responseData = _client.GetStringAsync(url).Result;

responseData在所有情况下均为null

我确信我错过了一些简单的事情。单元测试仍然是新的

有人能指出我哪里错了吗?

更新

完整的单元测试如下所示:

[Test]
public void Given_EController_Called_With_unknown_pedi_Returns_NotFound()
{
    // Arrange
    AppSettings settings = new AppSettings()
    {
        DataWarehouseAPI = "http://myurl.com"
    };
    Mock<IOptionsSnapshot<AppSettings>> mockSettings = new Mock<IOptionsSnapshot<AppSettings>>();
    mockSettings.Setup(m => m.Value).Returns(settings);

    var mockHttp = new Mock<IHttpClient>();
    mockHttp.Setup(m => m.GetStringAsync("aPretendUrl")).ReturnsAsync("[]");

    EntryController controller = new EntryController(mockHttp.Object, mockSettings.Object);

     // Act
    IActionResult actionResult = controller.GetByPedimento("nothing").Result;

    // Assert
    Assert.IsAssignableFrom<NotFoundObjectResult>(actionResult);
    }

1 个答案:

答案 0 :(得分:5)

如果您不关心测试中的'url',那么您可以使用:

It.IsAny<string>()

结果:

mockHttp.Setup(m => m.GetStringAsync(It.IsAny<string>()))
    .ReturnsAsync("Some sort of string");

如果在设置中指定'uri'参数,则必须在测试中将其匹配,以从方法中获得所需的返回值“某种字符串”。您可以为不同的输入指定不同的结果:

[TestMethod]
public async Task GetStringAsync_moqSetup()
{
    var mockHttp = new Mock<IHttpClient>();

    mockHttp.Setup(m => m.GetStringAsync(It.IsAny<string>()))
        .ReturnsAsync("Other sort of string");
    mockHttp.Setup(m => m.GetStringAsync("first"))
        .ReturnsAsync("First sort of string");

     var firstTarget = await mockHttp.Object.GetStringAsync("first");
     var differentTarget = await mockHttp.Object
         .GetStringAsync("something completely different");

    Assert.AreEqual("First sort of string", firstTarget);
    Assert.AreEqual("Other sort of string", differentTarget);
}

查看框架的Quickstart,以便更好地了解如何使用它。