using System; using System.Net; using System.Net.Http; using System.Threading.Tasks; using Moq; using NUnit.Framework; using SpotifyAPI.Web.Http; namespace SpotifyAPI.Web.Tests { [TestFixture] public class APIConnectorTest { [Test] public async Task RetryHandler_IsUsed() { var apiResponse = new Mock>(); apiResponse.SetupGet(a => a.Body).Returns("Hello World"); var response = new Mock(); response.SetupGet(r => r.ContentType).Returns("application/json"); response.SetupGet(r => r.StatusCode).Returns(HttpStatusCode.OK); response.SetupGet(r => r.Body).Returns("\"Hello World\""); var authenticator = new Mock(); var serializer = new Mock(); serializer.Setup(s => s.DeserializeResponse(It.IsAny())).Returns(apiResponse.Object); var httpClient = new Mock(); var retryHandler = new Mock(); retryHandler.Setup(r => r.HandleRetry( It.IsAny(), It.IsAny(), It.IsAny>>() ) ).Returns(Task.FromResult(response.Object)); var apiConnector = new APIConnector( new Uri("https://spotify.com"), authenticator.Object, serializer.Object, httpClient.Object, retryHandler.Object, null ); await apiConnector.SendAPIRequest(new Uri("/me", UriKind.Relative), HttpMethod.Get).ConfigureAwait(false); authenticator.Verify(a => a.Apply(It.IsAny(), It.IsAny()), Times.Once); httpClient.Verify(h => h.DoRequest(It.IsAny()), Times.Once); serializer.Verify(s => s.DeserializeResponse(response.Object), Times.Once); } [Test] public async Task RetryHandler_CanRetry() { var apiResponse = new Mock>(); apiResponse.SetupGet(a => a.Body).Returns("Hello World"); var response = new Mock(); response.SetupGet(r => r.ContentType).Returns("application/json"); response.SetupGet(r => r.StatusCode).Returns(HttpStatusCode.OK); response.SetupGet(r => r.Body).Returns("\"Hello World\""); var authenticator = new Mock(); var serializer = new Mock(); serializer.Setup(s => s.DeserializeResponse(It.IsAny())).Returns(apiResponse.Object); var httpClient = new Mock(); httpClient.Setup(h => h.DoRequest(It.IsAny())).Returns(Task.FromResult(response.Object)); var retryHandler = new Mock(); retryHandler.Setup(r => r.HandleRetry( It.IsAny(), It.IsAny(), It.IsAny>>() ) ).Returns((IRequest request, IResponse response, Func> retry) => retry(request)); var apiConnector = new APIConnector( new Uri("https://spotify.com"), authenticator.Object, serializer.Object, httpClient.Object, retryHandler.Object, null ); await apiConnector.SendAPIRequest(new Uri("/me", UriKind.Relative), HttpMethod.Get).ConfigureAwait(false); serializer.Verify(s => s.SerializeRequest(It.IsAny()), Times.Once); authenticator.Verify(a => a.Apply(It.IsAny(), It.IsAny()), Times.Exactly(2)); httpClient.Verify(h => h.DoRequest(It.IsAny()), Times.Exactly(2)); serializer.Verify(s => s.DeserializeResponse(response.Object), Times.Once); } } }