Jamie Rees
Jamie Rees

Reputation: 8183

How could I Mock this code?

I want to start mocking some code but I am unsure how to do it. I have read a few tutorials but I cannot apply it to my code (There maybe a reason behind it). I am using NUnit and Moq. (I have removed all other methods so I can just show you one).

Api Interface:

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

Method I want to Mock:

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

I'm not sure how I can mock this.

Update:

Is this now a valid test?

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

Upvotes: 1

Views: 1792

Answers (1)

NeddySpaghetti
NeddySpaghetti

Reputation: 13495

If you want to mock the ExecutAsync method you can do it like this:

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

if you want to mock for a particlur request, replace It.IsAny<RestRequest>() with a reference to your request.

To effectively test your class you need something like this:

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

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

Upvotes: 3

Related Questions