gpt4 book ai didi

c# - 模拟接口(interface) ReturnsAsync 返回 null

转载 作者:行者123 更新时间:2023-11-30 14:23:03 28 4
gpt4 key购买 nike

我正在尝试 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

在注入(inject)这个实例的 Controller 中,我这样调用它:

string responseData = await _client.GetStringAsync(url);

也在努力

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

responseDatanull在所有情况下。

我确信我遗漏了一些简单的东西。单元测试仍然是新的

谁能指出我哪里出错了?

更新

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

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

最佳答案

如果您不关心测试中的“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框架,以便更好地了解如何使用它。

关于c# - 模拟接口(interface) ReturnsAsync 返回 null,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47163503/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com