// Copyright (c) Microsoft Corporation. All rights reserved. See License.txt in the project root for license information. using System.Collections.Generic; using System.Net.Http.Formatting; using Moq; using Xunit; using Xunit.Extensions; using Assert = Microsoft.TestCommon.AssertEx; namespace System.Net.Http { public class HttpResponseMessageExtensionsTest { private readonly HttpResponseMessage _response = new HttpResponseMessage(); private readonly Mock _formatterMock = new Mock(); public HttpResponseMessageExtensionsTest() { _formatterMock.Setup(f => f.CanWriteType(It.IsAny())).Returns(true); } [Fact] public void TryGetContentValue_WhenResponseParameterIsNull_Throws() { object value; Assert.ThrowsArgumentNull(() => HttpResponseMessageExtensions.TryGetContentValue(null, out value), "response"); } [Theory] [InlineData(default(bool))] [InlineData(default(int))] [InlineData(default(object))] public void TryGetContentValue_WhenResponseHasNoContent_ReturnsFalse(T expectedResult) { T value; Assert.False(_response.TryGetContentValue(out value)); Assert.Equal(expectedResult, value); } [Theory] [InlineData(default(bool))] [InlineData(default(int))] [InlineData(default(object))] public void TryGetContentValue_WhenResponseHasNonObjectContent_ReturnsFalse(T expectedResult) { _response.Content = new StringContent("43"); T value; Assert.False(_response.TryGetContentValue(out value)); Assert.Equal(expectedResult, value); } [Theory] [InlineData(default(bool))] [InlineData(default(int))] [InlineData(default(object))] public void TryGetContentValue_WhenResponseHasObjectContentWithNullValue_ReturnsFalse(T expectedResult) { _response.Content = new ObjectContent(typeof(object), null, _formatterMock.Object); T value; Assert.False(_response.TryGetContentValue(out value)); Assert.Equal(expectedResult, value); } [Theory] [InlineData(default(bool))] [InlineData(default(int))] public void TryGetContentValue_WhenResponseHasObjectContentWithIncompatibleValue_ReturnsFalse(T expectedResult) { _response.Content = new ObjectContent("42", _formatterMock.Object); T value; Assert.False(_response.TryGetContentValue(out value)); Assert.Equal(expectedResult, value); } [Fact] public void TryGetContentValue_WhenResponseHasObjectContentWithCompatibleValue_ReturnsTrue() { List value = new List(); _response.Content = new ObjectContent>(value, _formatterMock.Object); IList result; Assert.True(_response.TryGetContentValue(out result)); Assert.Same(value, result); } [Fact] public void TryGetContentValue_WhenResponseHasObjectContentValueTypeValue_RetrievingAsObjectReturnsTrue() { _response.Content = new ObjectContent(32, _formatterMock.Object); object result; Assert.True(_response.TryGetContentValue(out result)); Assert.Equal(32, result); } } }