gpt4 book ai didi

c# - 我怎么能模拟这段代码?

转载 作者:太空宇宙 更新时间:2023-11-03 23:36:04 27 4
gpt4 key购买 nike

我想开始模拟一些代码,但我不确定该怎么做。我已经阅读了一些教程,但我无法将其应用到我的代码中(这背后可能是有原因的)。我正在使用 NUnit 和最小起订量。(我已经删除了所有其他方法,因此我只能向您展示一个)。

API接口(interface):

public interface IApiRequest
{
Task<T> ExecuteAsync<T>(RestRequest request);
}

我想模拟的方法:

public async Task<UpcomingMovies> GetUpcomingMovies(int page)
{
var request = new RestRequest
{
Resource = "movie/upcoming",
};
request.AddParameter("page", page.ToString());
request.AddParameter("language", "en");

var api = new ApiRequest();

return await api.ExecuteAsync<UpcomingMovies>(request);
}

我不确定如何模拟这个。

更新:

现在这是一个有效的测试吗?

 Mock<IApiRequest> mock = new Mock<IApiRequest>();
mock.Setup(x => x.ExecuteAsync<UpcomingMovies>(It.IsAny<RestRequest>()))
.Returns(Task.FromResult<UpcomingMovies>(new UpcomingMovies()));

最佳答案

如果你想模拟 ExecutAsync方法你可以这样做:

Mock<IApiRequest> mock = new Mock<IApiRequest>();
mock.Setup(x => x.ExecuteAsync<UpcomingMovies>(It.IsAny<RestRequest>()))
.Returns(Task.FromResult<UpcomingMovies>(/** whatever movies **/));

如果你想模拟一个特定的请求,替换It.IsAny<RestRequest>()引用您的请求。

为了有效地测试你的类,你需要这样的东西:

public class MyClass
{
public MyClass(IApiRequest api)
{
this.api = api;
}

public async Task<UpcomingMovies> GetUpcomingMovies(int page)
{
var request = new RestRequest
{
Resource = "movie/upcoming",
};
request.AddParameter("page", page.ToString());
request.AddParameter("language", "en");

return await api.ExecuteAsync<UpcomingMovies>(request);
}
}

测试

[Test]
public async Task MyTest()
{
var expectedMovies = new UpcomingMovies(); // or whatever movies you need

Mock<IApiRequest> mock = new Mock<IApiRequest>();
mock.Setup(x => x.ExecuteAsync<UpcomingMovies>(It.IsAny<RestRequest>()))
.Returns(Task.FromResult<UpcomingMovies>(expectedMovies));

var myClass = new MyClass(mock.Object);
var result = await myClass.GetUpcomingMovies(1);

Assert.IsTrue(expectedMovies == result);
}

关于c# - 我怎么能模拟这段代码?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30573122/

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