我怎么能模拟这段代码?

时间:2015-06-01 12:08:20

标签: c# unit-testing mocking nunit moq

我想开始嘲笑一些代码,但我不确定该怎么做。我已经阅读了一些教程,但我不能将它应用到我的代码中(可能有一个原因)。 我正在使用NUnit和Moq。 (我已经删除了所有其他方法,所以我只能告诉你一个。)

Api界面:

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()));

1 个答案:

答案 0 :(得分:3)

如果你想模仿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);    
}