Imported Upstream version 3.6.0

Former-commit-id: da6be194a6b1221998fc28233f2503bd61dd9d14
This commit is contained in:
Jo Shields
2014-08-13 10:39:27 +01:00
commit a575963da9
50588 changed files with 8155799 additions and 0 deletions

View File

@ -0,0 +1,117 @@
// 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;
using System.Threading;
using System.Threading.Tasks;
using System.Web.Http.Controllers;
using Moq;
using Xunit;
using Assert = Microsoft.TestCommon.AssertEx;
namespace System.Web.Http
{
public class ApiControllerActionInvokerTest
{
private readonly HttpActionContext _actionContext;
private readonly Mock<HttpActionDescriptor> _actionDescriptorMock = new Mock<HttpActionDescriptor>();
private readonly ApiControllerActionInvoker _actionInvoker = new ApiControllerActionInvoker();
private readonly HttpControllerContext _controllerContext;
private readonly HttpRequestMessage _request = new HttpRequestMessage();
private readonly Mock<IActionResultConverter> _converterMock = new Mock<IActionResultConverter>();
public ApiControllerActionInvokerTest()
{
_controllerContext = new HttpControllerContext()
{
Request = _request
};
_actionContext = new HttpActionContext(_controllerContext, _actionDescriptorMock.Object);
_actionDescriptorMock.Setup(ad => ad.ResultConverter).Returns(_converterMock.Object);
}
[Fact]
public void InvokeActionAsync_Cancels_IfCancellationTokenRequested()
{
CancellationTokenSource cancellationSource = new CancellationTokenSource();
cancellationSource.Cancel();
var response = _actionInvoker.InvokeActionAsync(ContextUtil.CreateActionContext(), cancellationSource.Token);
Assert.Equal<TaskStatus>(TaskStatus.Canceled, response.Status);
}
[Fact]
public void InvokeActionAsync_Throws_IfContextIsNull()
{
Assert.ThrowsArgumentNull(
() => _actionInvoker.InvokeActionAsync(null, CancellationToken.None),
"actionContext");
}
[Fact]
public void InvokeActionAsync_InvokesActionDescriptorExecuteAsync()
{
var result = _actionInvoker.InvokeActionAsync(_actionContext, CancellationToken.None);
result.WaitUntilCompleted();
_actionDescriptorMock.Verify(ad => ad.ExecuteAsync(_actionContext.ControllerContext, _actionContext.ActionArguments), Times.Once());
}
[Fact]
public void InvokeActionAsync_PassesExecutionResultToConfiguredConverter()
{
var value = new object();
_actionDescriptorMock.Setup(ad => ad.ExecuteAsync(_actionContext.ControllerContext, _actionContext.ActionArguments))
.Returns(TaskHelpers.FromResult(value));
var result = _actionInvoker.InvokeActionAsync(_actionContext, CancellationToken.None);
result.WaitUntilCompleted();
_converterMock.Verify(c => c.Convert(_actionContext.ControllerContext, value), Times.Once());
}
[Fact]
public void InvokeActionAsync_ReturnsResponseFromConverter()
{
var response = new HttpResponseMessage();
_actionDescriptorMock.Setup(ad => ad.ExecuteAsync(_actionContext.ControllerContext, _actionContext.ActionArguments))
.Returns(TaskHelpers.FromResult(new object()));
_converterMock.Setup(c => c.Convert(_actionContext.ControllerContext, It.IsAny<object>()))
.Returns(response);
var result = _actionInvoker.InvokeActionAsync(_actionContext, CancellationToken.None);
result.WaitUntilCompleted();
Assert.Same(response, result.Result);
}
[Fact]
public void InvokeActionAsync_WhenExecuteThrowsHttpResponseException_ReturnsResponse()
{
HttpResponseMessage response = new HttpResponseMessage();
_actionDescriptorMock.Setup(ad => ad.ExecuteAsync(It.IsAny<HttpControllerContext>(), It.IsAny<IDictionary<string, object>>()))
.Throws(new HttpResponseException(response));
var result = _actionInvoker.InvokeActionAsync(_actionContext, CancellationToken.None);
result.WaitUntilCompleted();
Assert.Same(response, result.Result);
Assert.Same(_request, result.Result.RequestMessage);
}
[Fact]
public void InvokeActionAsync_WhenExecuteThrows_ReturnsFaultedTask()
{
Exception exception = new Exception();
_actionDescriptorMock.Setup(ad => ad.ExecuteAsync(It.IsAny<HttpControllerContext>(), It.IsAny<IDictionary<string, object>>()))
.Throws(exception);
var result = _actionInvoker.InvokeActionAsync(_actionContext, CancellationToken.None);
result.WaitUntilCompleted();
Assert.Equal(TaskStatus.Faulted, result.Status);
Assert.Same(exception, result.Exception.GetBaseException());
}
}
}

View File

@ -0,0 +1,49 @@
// Copyright (c) Microsoft Corporation. All rights reserved. See License.txt in the project root for license information.
using System.Net.Http;
using System.Web.Http.Controllers;
using Xunit;
using Assert = Microsoft.TestCommon.AssertEx;
namespace System.Web.Http
{
public class ApiControllerActionSelectorTest
{
[Fact]
public void SelectAction_With_DifferentExecutionContexts()
{
ApiControllerActionSelector actionSelector = new ApiControllerActionSelector();
HttpControllerContext GetContext = ContextUtil.CreateControllerContext();
HttpControllerDescriptor usersControllerDescriptor = new HttpControllerDescriptor(GetContext.Configuration, "Users", typeof(UsersController));
usersControllerDescriptor.HttpActionSelector = actionSelector;
GetContext.ControllerDescriptor = usersControllerDescriptor;
GetContext.Request = new HttpRequestMessage
{
Method = HttpMethod.Get
};
HttpControllerContext PostContext = ContextUtil.CreateControllerContext();
usersControllerDescriptor.HttpActionSelector = actionSelector;
PostContext.ControllerDescriptor = usersControllerDescriptor;
PostContext.Request = new HttpRequestMessage
{
Method = HttpMethod.Post
};
HttpActionDescriptor getActionDescriptor = actionSelector.SelectAction(GetContext);
HttpActionDescriptor postActionDescriptor = actionSelector.SelectAction(PostContext);
Assert.Equal("Get", getActionDescriptor.ActionName);
Assert.Equal("Post", postActionDescriptor.ActionName);
}
[Fact]
public void SelectAction_Throws_IfContextIsNull()
{
ApiControllerActionSelector actionSelector = new ApiControllerActionSelector();
Assert.ThrowsArgumentNull(
() => actionSelector.SelectAction(null),
"controllerContext");
}
}
}

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,11 @@
// Copyright (c) Microsoft Corporation. All rights reserved. See License.txt in the project root for license information.
namespace System.Web.Http
{
public class User
{
public string FirstName { get; set; }
public string LastName { get; set; }
}
}

View File

@ -0,0 +1,42 @@
// Copyright (c) Microsoft Corporation. All rights reserved. See License.txt in the project root for license information.
using System.Net;
using System.Net.Http;
namespace System.Web.Http
{
public class UsersController : ApiController
{
public HttpResponseMessage Get()
{
return new HttpResponseMessage(HttpStatusCode.OK)
{
Content = new StringContent("Default User")
};
}
public HttpResponseMessage Post()
{
return new HttpResponseMessage(HttpStatusCode.OK)
{
Content = new StringContent("User Posted")
};
}
public HttpResponseMessage Put()
{
return new HttpResponseMessage(HttpStatusCode.OK)
{
Content = new StringContent("User Updated")
};
}
public HttpResponseMessage Delete()
{
return new HttpResponseMessage(HttpStatusCode.OK)
{
Content = new StringContent("User Deleted")
};
}
}
}

View File

@ -0,0 +1,84 @@
// Copyright (c) Microsoft Corporation. All rights reserved. See License.txt in the project root for license information.
using System.Threading.Tasks;
namespace System.Web.Http
{
public class UsersRpcController : ApiController
{
public User EchoUser(string firstName, string lastName)
{
return new User()
{
FirstName = firstName,
LastName = lastName,
};
}
public Task<User> EchoUserAsync(string firstName, string lastName)
{
return TaskHelpers.FromResult(new User()
{
FirstName = firstName,
LastName = lastName,
});
}
[Authorize]
[HttpGet]
public User AddAdmin(string firstName, string lastName)
{
return new User()
{
FirstName = firstName,
LastName = lastName,
};
}
public User RetriveUser(int id)
{
return new User()
{
LastName = "UserLN" + id,
FirstName = "UserFN" + id
};
}
public User EchoUserObject(User user)
{
return user;
}
public User Admin()
{
return new User
{
FirstName = "Yao",
LastName = "Huang"
};
}
public void DeleteAllUsers()
{
}
public Task DeleteAllUsersAsync()
{
return TaskHelpers.Completed();
}
public void AddUser([FromBody] User user)
{
}
public Task WrappedTaskReturningMethod()
{
return TaskHelpers.FromResult(TaskHelpers.Completed());
}
public object TaskAsObjectReturningMethod()
{
return TaskHelpers.Completed();
}
}
}

View File

@ -0,0 +1,78 @@
// Copyright (c) Microsoft Corporation. All rights reserved. See License.txt in the project root for license information.
using System.Web.Http.Controllers;
using Moq;
using Xunit;
using Assert = Microsoft.TestCommon.AssertEx;
namespace System.Web.Http
{
public class HttpActionContextTest
{
[Fact]
public void Default_Constructor()
{
HttpActionContext actionContext = new HttpActionContext();
Assert.Null(actionContext.ControllerContext);
Assert.Null(actionContext.ActionDescriptor);
Assert.Null(actionContext.Response);
Assert.Null(actionContext.Request);
Assert.NotNull(actionContext.ActionArguments);
Assert.NotNull(actionContext.ModelState);
}
[Fact]
public void Parameter_Constructor()
{
HttpControllerContext controllerContext = ContextUtil.CreateControllerContext();
HttpActionDescriptor actionDescriptor = new Mock<HttpActionDescriptor>().Object;
HttpActionContext actionContext = new HttpActionContext(controllerContext, actionDescriptor);
Assert.Same(controllerContext, actionContext.ControllerContext);
Assert.Same(actionDescriptor, actionContext.ActionDescriptor);
Assert.Same(controllerContext.Request, actionContext.Request);
Assert.Null(actionContext.Response);
Assert.NotNull(actionContext.ActionArguments);
Assert.NotNull(actionContext.ModelState);
}
[Fact]
public void Constructor_Throws_IfControllerContextIsNull()
{
Assert.ThrowsArgumentNull(
() => new HttpActionContext(null, new Mock<HttpActionDescriptor>().Object),
"controllerContext");
}
[Fact]
public void Constructor_Throws_IfActionDescriptorIsNull()
{
Assert.ThrowsArgumentNull(
() => new HttpActionContext(ContextUtil.CreateControllerContext(), null),
"actionDescriptor");
}
[Fact]
public void ControllerContext_Property()
{
Assert.Reflection.Property<HttpActionContext, HttpControllerContext>(
instance: new HttpActionContext(),
propertyGetter: ac => ac.ControllerContext,
expectedDefaultValue: null,
allowNull: false,
roundTripTestValue: ContextUtil.CreateControllerContext());
}
[Fact]
public void ActionDescriptor_Property()
{
Assert.Reflection.Property<HttpActionContext, HttpActionDescriptor>(
instance: new HttpActionContext(),
propertyGetter: ac => ac.ActionDescriptor,
expectedDefaultValue: null,
allowNull: false,
roundTripTestValue: new Mock<HttpActionDescriptor>().Object);
}
}
}

View File

@ -0,0 +1,38 @@
// Copyright (c) Microsoft Corporation. All rights reserved. See License.txt in the project root for license information.
using System.Net.Http;
using Xunit;
using Xunit.Extensions;
using Assert = Microsoft.TestCommon.AssertEx;
namespace System.Web.Http.Controllers
{
public class HttpActionDescriptorTest
{
[Theory]
[InlineData(null, typeof(VoidResultConverter))]
[InlineData(typeof(HttpResponseMessage), typeof(ResponseMessageResultConverter))]
[InlineData(typeof(object), typeof(ValueResultConverter<object>))]
[InlineData(typeof(string), typeof(ValueResultConverter<string>))]
public void GetResultConverter_GetAppropriateConverterInstance(Type actionReturnType, Type expectedConverterType)
{
var result = HttpActionDescriptor.GetResultConverter(actionReturnType);
Assert.IsType(expectedConverterType, result);
}
[Fact]
public void GetResultConverter_WhenTypeIsAnGenericParameterType_Throws()
{
var genericType = typeof(HttpActionDescriptorTest).GetMethod("SampleGenericMethod").ReturnType;
Assert.Throws<InvalidOperationException>(() => HttpActionDescriptor.GetResultConverter(genericType),
"No action result converter could be constructed for a generic parameter type 'TResult'.");
}
public TResult SampleGenericMethod<TResult>()
{
return default(TResult);
}
}
}

View File

@ -0,0 +1,78 @@
// Copyright (c) Microsoft Corporation. All rights reserved. See License.txt in the project root for license information.
using System.Web.Http.Services;
using Microsoft.TestCommon;
using Moq;
using Xunit;
using Assert = Microsoft.TestCommon.AssertEx;
namespace System.Web.Http
{
public class HttpConfigurationTest
{
[Fact]
public void TypeIsCorrect()
{
Assert.Type.HasProperties<HttpConfiguration>(TypeAssert.TypeProperties.IsPublicVisibleClass | TypeAssert.TypeProperties.IsDisposable);
}
[Fact]
public void Default_Constructor()
{
HttpConfiguration configuration = new HttpConfiguration();
Assert.Empty(configuration.Filters);
Assert.NotEmpty(configuration.Formatters);
Assert.Empty(configuration.MessageHandlers);
Assert.Empty(configuration.Properties);
Assert.Empty(configuration.Routes);
Assert.NotNull(configuration.DependencyResolver);
Assert.NotNull(configuration.Services);
Assert.Equal("/", configuration.VirtualPathRoot);
}
[Fact]
public void Parameter_Constructor()
{
string path = "/some/path";
HttpRouteCollection routes = new HttpRouteCollection(path);
HttpConfiguration configuration = new HttpConfiguration(routes);
Assert.Same(routes, configuration.Routes);
Assert.Equal(path, configuration.VirtualPathRoot);
}
[Fact]
public void Dispose_Idempotent()
{
HttpConfiguration configuration = new HttpConfiguration();
configuration.Dispose();
configuration.Dispose();
}
[Fact]
public void Dispose_DisposesOfServices()
{
// Arrange
var configuration = new HttpConfiguration();
var services = new Mock<DefaultServices> { CallBase = true };
configuration.Services = services.Object;
// Act
configuration.Dispose();
// Assert
services.Verify(s => s.Dispose(), Times.Once());
}
[Fact]
public void DependencyResolver_GuardClauses()
{
// Arrange
var config = new HttpConfiguration();
// Act & assert
Assert.ThrowsArgumentNull(() => config.DependencyResolver = null, "value");
}
}
}

View File

@ -0,0 +1,110 @@
// Copyright (c) Microsoft Corporation. All rights reserved. See License.txt in the project root for license information.
using System.Net.Http;
using System.Web.Http.Controllers;
using System.Web.Http.Routing;
using Moq;
using Xunit;
using Assert = Microsoft.TestCommon.AssertEx;
namespace System.Web.Http
{
public class HttpControllerContextTest
{
[Fact]
public void Default_Constructor()
{
HttpControllerContext controllerContext = new HttpControllerContext();
Assert.Null(controllerContext.Configuration);
Assert.Null(controllerContext.Controller);
Assert.Null(controllerContext.ControllerDescriptor);
Assert.Null(controllerContext.Request);
Assert.Null(controllerContext.RouteData);
}
[Fact]
public void Parameter_Constructor()
{
HttpConfiguration config = new HttpConfiguration();
IHttpRouteData routeData = new Mock<IHttpRouteData>().Object;
HttpRequestMessage request = new HttpRequestMessage();
HttpControllerContext controllerContext = new HttpControllerContext(config, routeData, request);
Assert.Same(config, controllerContext.Configuration);
Assert.Same(request, controllerContext.Request);
Assert.Same(routeData, controllerContext.RouteData);
Assert.Null(controllerContext.Controller);
Assert.Null(controllerContext.ControllerDescriptor);
}
[Fact]
public void Constructor_Throws_IfConfigurationIsNull()
{
Assert.ThrowsArgumentNull(
() => new HttpControllerContext(null, new Mock<IHttpRouteData>().Object, new HttpRequestMessage()),
"configuration");
}
[Fact]
public void Constructor_Throws_IfRouteDataIsNull()
{
Assert.ThrowsArgumentNull(
() => new HttpControllerContext(new HttpConfiguration(), null, new HttpRequestMessage()),
"routeData");
}
[Fact]
public void Constructor_Throws_IfRequestIsNull()
{
Assert.ThrowsArgumentNull(
() => new HttpControllerContext(new HttpConfiguration(), new Mock<IHttpRouteData>().Object, null),
"request");
}
[Fact]
public void Configuration_Property()
{
Assert.Reflection.Property<HttpControllerContext, HttpConfiguration>(
instance: new HttpControllerContext(),
propertyGetter: cc => cc.Configuration,
expectedDefaultValue: null,
allowNull: false,
roundTripTestValue: new HttpConfiguration());
}
[Fact]
public void Controller_Property()
{
Assert.Reflection.Property<HttpControllerContext, IHttpController>(
instance: new HttpControllerContext(),
propertyGetter: cc => cc.Controller,
expectedDefaultValue: null,
allowNull: false,
roundTripTestValue: new Mock<IHttpController>().Object);
}
[Fact]
public void ControllerDescriptor_Property()
{
Assert.Reflection.Property<HttpControllerContext, HttpControllerDescriptor>(
instance: new HttpControllerContext(),
propertyGetter: cc => cc.ControllerDescriptor,
expectedDefaultValue: null,
allowNull: false,
roundTripTestValue: new HttpControllerDescriptor());
}
[Fact]
public void RouteData_Property()
{
Assert.Reflection.Property<HttpControllerContext, IHttpRouteData>(
instance: new HttpControllerContext(),
propertyGetter: cc => cc.RouteData,
expectedDefaultValue: null,
allowNull: false,
roundTripTestValue: new Mock<IHttpRouteData>().Object);
}
}
}

View File

@ -0,0 +1,185 @@
// Copyright (c) Microsoft Corporation. All rights reserved. See License.txt in the project root for license information.
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Web.Http.Controllers;
using System.Web.Http.Dispatcher;
using System.Web.Http.Filters;
using Moq;
using Xunit;
using Assert = Microsoft.TestCommon.AssertEx;
namespace System.Web.Http
{
public class HttpControllerDescriptorTest
{
[Fact]
public void Default_Constructor()
{
HttpControllerDescriptor controllerDescriptor = new HttpControllerDescriptor();
Assert.Null(controllerDescriptor.ControllerName);
Assert.Null(controllerDescriptor.Configuration);
Assert.Null(controllerDescriptor.ControllerType);
Assert.Null(controllerDescriptor.HttpActionInvoker);
Assert.Null(controllerDescriptor.HttpActionSelector);
Assert.Null(controllerDescriptor.HttpControllerActivator);
Assert.NotNull(controllerDescriptor.Properties);
}
[Fact]
public void Parameter_Constructor()
{
HttpConfiguration config = new HttpConfiguration();
string controllerName = "UsersController";
Type controllerType = typeof(UsersController);
HttpControllerDescriptor controllerDescriptor = new HttpControllerDescriptor(config, controllerName, controllerType);
Assert.NotNull(controllerDescriptor.ControllerName);
Assert.NotNull(controllerDescriptor.Configuration);
Assert.NotNull(controllerDescriptor.ControllerType);
Assert.NotNull(controllerDescriptor.HttpActionInvoker);
Assert.NotNull(controllerDescriptor.HttpActionSelector);
Assert.NotNull(controllerDescriptor.HttpControllerActivator);
Assert.NotNull(controllerDescriptor.Properties);
Assert.Equal(config, controllerDescriptor.Configuration);
Assert.Equal(controllerName, controllerDescriptor.ControllerName);
Assert.Equal(controllerType, controllerDescriptor.ControllerType);
}
[Fact]
public void Constructor_Throws_IfConfigurationIsNull()
{
Assert.ThrowsArgumentNull(
() => new HttpControllerDescriptor(null, "UsersController", typeof(UsersController)),
"configuration");
}
[Fact]
public void Constructor_Throws_IfControllerNameIsNull()
{
Assert.ThrowsArgumentNull(
() => new HttpControllerDescriptor(new HttpConfiguration(), null, typeof(UsersController)),
"controllerName");
}
[Fact]
public void Constructor_Throws_IfControllerTypeIsNull()
{
Assert.ThrowsArgumentNull(
() => new HttpControllerDescriptor(new HttpConfiguration(), "UsersController", null),
"controllerType");
}
[Fact]
public void Configuration_Property()
{
HttpConfiguration config = new HttpConfiguration();
HttpControllerDescriptor controllerDescriptor = new HttpControllerDescriptor();
Assert.Reflection.Property<HttpControllerDescriptor, HttpConfiguration>(
instance: controllerDescriptor,
propertyGetter: cd => cd.Configuration,
expectedDefaultValue: null,
allowNull: false,
roundTripTestValue: config);
}
[Fact]
public void ControllerName_Property()
{
string controllerName = "UsersController";
HttpControllerDescriptor controllerDescriptor = new HttpControllerDescriptor();
Assert.Reflection.Property<HttpControllerDescriptor, string>(
instance: controllerDescriptor,
propertyGetter: cd => cd.ControllerName,
expectedDefaultValue: null,
allowNull: false,
roundTripTestValue: controllerName);
}
[Fact]
public void ControllerType_Property()
{
Type controllerType = typeof(UsersController);
HttpControllerDescriptor controllerDescriptor = new HttpControllerDescriptor();
Assert.Reflection.Property<HttpControllerDescriptor, Type>(
instance: controllerDescriptor,
propertyGetter: cd => cd.ControllerType,
expectedDefaultValue: null,
allowNull: false,
roundTripTestValue: controllerType);
}
[Fact]
public void HttpActionInvoker_Property()
{
IHttpActionInvoker invoker = new ApiControllerActionInvoker();
HttpControllerDescriptor controllerDescriptor = new HttpControllerDescriptor();
Assert.Reflection.Property<HttpControllerDescriptor, IHttpActionInvoker>(
instance: controllerDescriptor,
propertyGetter: cd => cd.HttpActionInvoker,
expectedDefaultValue: null,
allowNull: false,
roundTripTestValue: invoker);
}
[Fact]
public void HttpActionSelector_Property()
{
IHttpActionSelector selector = new ApiControllerActionSelector();
HttpControllerDescriptor controllerDescriptor = new HttpControllerDescriptor();
Assert.Reflection.Property<HttpControllerDescriptor, IHttpActionSelector>(
instance: controllerDescriptor,
propertyGetter: cd => cd.HttpActionSelector,
expectedDefaultValue: null,
allowNull: false,
roundTripTestValue: selector);
}
[Fact]
public void HttpControllerActivator_Property()
{
IHttpControllerActivator activator = new Mock<IHttpControllerActivator>().Object;
HttpControllerDescriptor controllerDescriptor = new HttpControllerDescriptor();
Assert.Reflection.Property<HttpControllerDescriptor, IHttpControllerActivator>(
instance: controllerDescriptor,
propertyGetter: cd => cd.HttpControllerActivator,
expectedDefaultValue: null,
allowNull: false,
roundTripTestValue: activator);
}
[Fact]
public void ActionValueBinder_Property()
{
IActionValueBinder activator = new Mock<IActionValueBinder>().Object;
HttpControllerDescriptor controllerDescriptor = new HttpControllerDescriptor();
Assert.Reflection.Property<HttpControllerDescriptor, IActionValueBinder>(
instance: controllerDescriptor,
propertyGetter: cd => cd.ActionValueBinder,
expectedDefaultValue: null,
allowNull: false,
roundTripTestValue: activator);
}
[Fact]
public void GetFilters_InvokesGetCustomAttributesMethod()
{
var descriptorMock = new Mock<HttpControllerDescriptor> { CallBase = true };
var filters = new Collection<IFilter>(new List<IFilter>());
descriptorMock.Setup(d => d.GetCustomAttributes<IFilter>()).Returns(filters).Verifiable();
var result = descriptorMock.Object.GetFilters();
Assert.Same(filters, result);
descriptorMock.Verify();
}
}
}

View File

@ -0,0 +1,75 @@
// Copyright (c) Microsoft Corporation. All rights reserved. See License.txt in the project root for license information.
using System.Collections.Generic;
using System.Linq;
using System.Web.Http.Controllers;
using Moq;
using Xunit;
using Assert = Microsoft.TestCommon.AssertEx;
namespace System.Web.Http
{
public class HttpParameterDescriptorTest
{
[Fact]
public void Default_Constructor()
{
HttpParameterDescriptor parameterDescriptor = new Mock<HttpParameterDescriptor>().Object;
Assert.Null(parameterDescriptor.ParameterName);
Assert.Null(parameterDescriptor.ParameterType);
Assert.Null(parameterDescriptor.Configuration);
Assert.Null(parameterDescriptor.Prefix);
Assert.Null(parameterDescriptor.ModelBinderAttribute);
Assert.Null(parameterDescriptor.ActionDescriptor);
Assert.Null(parameterDescriptor.DefaultValue);
Assert.NotNull(parameterDescriptor.Properties);
}
[Fact]
public void Configuration_Property()
{
HttpConfiguration config = new HttpConfiguration();
HttpParameterDescriptor parameterDescriptor = new Mock<HttpParameterDescriptor> { CallBase = true }.Object;
Assert.Reflection.Property<HttpParameterDescriptor, HttpConfiguration>(
instance: parameterDescriptor,
propertyGetter: pd => pd.Configuration,
expectedDefaultValue: null,
allowNull: false,
roundTripTestValue: config);
}
[Fact]
public void ActionDescriptor_Property()
{
HttpParameterDescriptor parameterDescriptor = new Mock<HttpParameterDescriptor> { CallBase = true }.Object;
HttpActionDescriptor actionDescriptor = new Mock<HttpActionDescriptor>().Object;
Assert.Reflection.Property<HttpParameterDescriptor, HttpActionDescriptor>(
instance: parameterDescriptor,
propertyGetter: pd => pd.ActionDescriptor,
expectedDefaultValue: null,
allowNull: false,
roundTripTestValue: actionDescriptor);
}
[Fact]
public void GetCustomAttributes_Returns_EmptyAttributes()
{
HttpParameterDescriptor parameterDescriptor = new Mock<HttpParameterDescriptor> { CallBase = true }.Object;
IEnumerable<object> attributes = parameterDescriptor.GetCustomAttributes<object>();
Assert.Equal(0, attributes.Count());
}
[Fact]
public void GetCustomAttributes_AttributeType_Returns_EmptyAttributes()
{
HttpParameterDescriptor parameterDescriptor = new Mock<HttpParameterDescriptor> { CallBase = true }.Object;
IEnumerable<FromBodyAttribute> attributes = parameterDescriptor.GetCustomAttributes<FromBodyAttribute>();
Assert.Equal(0, attributes.Count());
}
}
}

View File

@ -0,0 +1,342 @@
// Copyright (c) Microsoft Corporation. All rights reserved. See License.txt in the project root for license information.
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Reflection;
using System.Threading.Tasks;
using System.Web.Http.Controllers;
using System.Web.Http.Filters;
using Moq;
using Xunit;
using Xunit.Extensions;
using Assert = Microsoft.TestCommon.AssertEx;
namespace System.Web.Http
{
public class ReflectedHttpActionDescriptorTest
{
private readonly UsersRpcController _controller = new UsersRpcController();
private readonly HttpControllerContext _context;
private readonly Dictionary<string, object> _arguments = new Dictionary<string, object>();
public ReflectedHttpActionDescriptorTest()
{
_context = ContextUtil.CreateControllerContext(instance: _controller);
}
[Fact]
public void Default_Constructor()
{
ReflectedHttpActionDescriptor actionDescriptor = new ReflectedHttpActionDescriptor();
Assert.Null(actionDescriptor.ActionName);
Assert.Null(actionDescriptor.Configuration);
Assert.Null(actionDescriptor.ControllerDescriptor);
Assert.Null(actionDescriptor.MethodInfo);
Assert.Null(actionDescriptor.ReturnType);
Assert.NotNull(actionDescriptor.Properties);
}
[Fact]
public void Parameter_Constructor()
{
Func<string, string, User> echoUserMethod = _controller.EchoUser;
HttpConfiguration config = new HttpConfiguration();
HttpControllerDescriptor controllerDescriptor = new HttpControllerDescriptor(config, "", typeof(UsersRpcController));
ReflectedHttpActionDescriptor actionDescriptor = new ReflectedHttpActionDescriptor(controllerDescriptor, echoUserMethod.Method);
Assert.Equal("EchoUser", actionDescriptor.ActionName);
Assert.Equal(config, actionDescriptor.Configuration);
Assert.Equal(typeof(UsersRpcController), actionDescriptor.ControllerDescriptor.ControllerType);
Assert.Equal(echoUserMethod.Method, actionDescriptor.MethodInfo);
Assert.Equal(typeof(User), actionDescriptor.ReturnType);
Assert.NotNull(actionDescriptor.Properties);
}
[Fact]
public void Constructor_Throws_IfMethodInfoIsNull()
{
Assert.ThrowsArgumentNull(
() => new ReflectedHttpActionDescriptor(new HttpControllerDescriptor(), null),
"methodInfo");
}
[Fact]
public void MethodInfo_Property()
{
ReflectedHttpActionDescriptor actionDescriptor = new ReflectedHttpActionDescriptor();
Action action = new Action(() => { });
Assert.Reflection.Property<ReflectedHttpActionDescriptor, MethodInfo>(
instance: actionDescriptor,
propertyGetter: ad => ad.MethodInfo,
expectedDefaultValue: null,
allowNull: false,
roundTripTestValue: action.Method);
}
[Fact]
public void ControllerDescriptor_Property()
{
ReflectedHttpActionDescriptor actionDescriptor = new ReflectedHttpActionDescriptor();
HttpControllerDescriptor controllerDescriptor = new HttpControllerDescriptor();
Assert.Reflection.Property<ReflectedHttpActionDescriptor, HttpControllerDescriptor>(
instance: actionDescriptor,
propertyGetter: ad => ad.ControllerDescriptor,
expectedDefaultValue: null,
allowNull: false,
roundTripTestValue: controllerDescriptor);
}
[Fact]
public void Configuration_Property()
{
ReflectedHttpActionDescriptor actionDescriptor = new ReflectedHttpActionDescriptor();
HttpConfiguration config = new HttpConfiguration();
Assert.Reflection.Property<ReflectedHttpActionDescriptor, HttpConfiguration>(
instance: actionDescriptor,
propertyGetter: ad => ad.Configuration,
expectedDefaultValue: null,
allowNull: false,
roundTripTestValue: config);
}
[Fact]
public void GetFilter_Returns_AttributedFilter()
{
Func<string, string, User> echoUserMethod = _controller.AddAdmin;
ReflectedHttpActionDescriptor actionDescriptor = new ReflectedHttpActionDescriptor { MethodInfo = echoUserMethod.Method };
_arguments["firstName"] = "test";
_arguments["lastName"] = "unit";
IEnumerable<IFilter> filters = actionDescriptor.GetFilters();
Assert.NotNull(filters);
Assert.Equal(1, filters.Count());
Assert.Equal(typeof(AuthorizeAttribute), filters.First().GetType());
}
[Fact]
public void GetFilterPipeline_Returns_ConfigurationFilters()
{
IActionFilter actionFilter = new Mock<IActionFilter>().Object;
IExceptionFilter exceptionFilter = new Mock<IExceptionFilter>().Object;
IAuthorizationFilter authorizationFilter = new AuthorizeAttribute();
Action deleteAllUsersMethod = _controller.DeleteAllUsers;
HttpControllerDescriptor controllerDescriptor = new HttpControllerDescriptor(new HttpConfiguration(), "UsersRpcController", typeof(UsersRpcController));
controllerDescriptor.Configuration.Filters.Add(actionFilter);
controllerDescriptor.Configuration.Filters.Add(exceptionFilter);
controllerDescriptor.Configuration.Filters.Add(authorizationFilter);
ReflectedHttpActionDescriptor actionDescriptor = new ReflectedHttpActionDescriptor(controllerDescriptor, deleteAllUsersMethod.Method);
Collection<FilterInfo> filters = actionDescriptor.GetFilterPipeline();
Assert.Same(actionFilter, filters[0].Instance);
Assert.Same(exceptionFilter, filters[1].Instance);
Assert.Same(authorizationFilter, filters[2].Instance);
}
[Fact]
public void GetCustomAttributes_Returns_ActionAttributes()
{
Func<string, string, User> echoUserMethod = _controller.AddAdmin;
ReflectedHttpActionDescriptor actionDescriptor = new ReflectedHttpActionDescriptor { MethodInfo = echoUserMethod.Method };
IEnumerable<IFilter> filters = actionDescriptor.GetCustomAttributes<IFilter>();
IEnumerable<HttpGetAttribute> httpGet = actionDescriptor.GetCustomAttributes<HttpGetAttribute>();
Assert.NotNull(filters);
Assert.Equal(1, filters.Count());
Assert.Equal(typeof(AuthorizeAttribute), filters.First().GetType());
Assert.NotNull(httpGet);
Assert.Equal(1, httpGet.Count());
}
[Fact]
public void GetParameters_Returns_ActionParameters()
{
Func<string, string, User> echoUserMethod = _controller.EchoUser;
ReflectedHttpActionDescriptor actionDescriptor = new ReflectedHttpActionDescriptor { MethodInfo = echoUserMethod.Method };
Collection<HttpParameterDescriptor> parameterDescriptors = actionDescriptor.GetParameters();
Assert.Equal(2, parameterDescriptors.Count);
Assert.NotNull(parameterDescriptors.Where(p => p.ParameterName == "firstName").FirstOrDefault());
Assert.NotNull(parameterDescriptors.Where(p => p.ParameterName == "lastName").FirstOrDefault());
}
[Fact]
public void ExecuteAsync_Returns_TaskOfNull_ForVoidAction()
{
Action deleteAllUsersMethod = _controller.DeleteAllUsers;
ReflectedHttpActionDescriptor actionDescriptor = new ReflectedHttpActionDescriptor { MethodInfo = deleteAllUsersMethod.Method };
Task<object> returnValue = actionDescriptor.ExecuteAsync(_context, _arguments);
returnValue.WaitUntilCompleted();
Assert.Null(returnValue.Result);
}
[Fact]
public void ExecuteAsync_Returns_Results_ForNonVoidAction()
{
Func<string, string, User> echoUserMethod = _controller.EchoUser;
ReflectedHttpActionDescriptor actionDescriptor = new ReflectedHttpActionDescriptor { MethodInfo = echoUserMethod.Method };
_arguments["firstName"] = "test";
_arguments["lastName"] = "unit";
Task<object> result = actionDescriptor.ExecuteAsync(_context, _arguments);
result.WaitUntilCompleted();
var returnValue = Assert.IsType<User>(result.Result);
Assert.Equal("test", returnValue.FirstName);
Assert.Equal("unit", returnValue.LastName);
}
[Fact]
public void ExecuteAsync_Returns_TaskOfNull_ForTaskAction()
{
Func<Task> deleteAllUsersMethod = _controller.DeleteAllUsersAsync;
ReflectedHttpActionDescriptor actionDescriptor = new ReflectedHttpActionDescriptor { MethodInfo = deleteAllUsersMethod.Method };
Task<object> returnValue = actionDescriptor.ExecuteAsync(_context, _arguments);
returnValue.WaitUntilCompleted();
Assert.Null(returnValue.Result);
}
[Fact]
public void ExecuteAsync_Returns_Results_ForTaskOfTAction()
{
Func<string, string, Task<User>> echoUserMethod = _controller.EchoUserAsync;
ReflectedHttpActionDescriptor actionDescriptor = new ReflectedHttpActionDescriptor { MethodInfo = echoUserMethod.Method };
_arguments["firstName"] = "test";
_arguments["lastName"] = "unit";
Task<object> result = actionDescriptor.ExecuteAsync(_context, _arguments);
result.WaitUntilCompleted();
var returnValue = Assert.IsType<User>(result.Result);
Assert.Equal("test", returnValue.FirstName);
Assert.Equal("unit", returnValue.LastName);
}
[Fact]
public void ExecuteAsync_Throws_IfContextIsNull()
{
Func<string, string, User> echoUserMethod = _controller.EchoUser;
ReflectedHttpActionDescriptor actionDescriptor = new ReflectedHttpActionDescriptor { MethodInfo = echoUserMethod.Method };
Assert.ThrowsArgumentNull(
() => actionDescriptor.ExecuteAsync(null, _arguments),
"controllerContext");
}
[Fact]
public void ExecuteAsync_Throws_IfArgumentsIsNull()
{
Func<string, string, User> echoUserMethod = _controller.EchoUser;
ReflectedHttpActionDescriptor actionDescriptor = new ReflectedHttpActionDescriptor { MethodInfo = echoUserMethod.Method };
Assert.ThrowsArgumentNull(
() => actionDescriptor.ExecuteAsync(_context, null).RethrowFaultedTaskException(),
"arguments");
}
[Fact]
public void ExecuteAsync_Throws_IfValueTypeArgumentsIsNull()
{
Func<int, User> retrieveUserMethod = _controller.RetriveUser;
ReflectedHttpActionDescriptor actionDescriptor = new ReflectedHttpActionDescriptor { MethodInfo = retrieveUserMethod.Method };
_arguments["id"] = null;
var exception = Assert.Throws<HttpResponseException>(
() => actionDescriptor.ExecuteAsync(_context, _arguments).RethrowFaultedTaskException());
Assert.Equal(HttpStatusCode.BadRequest, exception.Response.StatusCode);
var content = Assert.IsType<ObjectContent<string>>(exception.Response.Content);
Assert.Equal("The parameters dictionary contains a null entry for parameter 'id' of non-nullable type 'System.Int32' " +
"for method 'System.Web.Http.User RetriveUser(Int32)' in 'System.Web.Http.UsersRpcController'. An optional parameter " +
"must be a reference type, a nullable type, or be declared as an optional parameter.",
content.Value);
}
[Fact]
public void ExecuteAsync_Throws_IfArgumentNameIsWrong()
{
Func<int, User> retrieveUserMethod = _controller.RetriveUser;
ReflectedHttpActionDescriptor actionDescriptor = new ReflectedHttpActionDescriptor { MethodInfo = retrieveUserMethod.Method };
_arguments["otherId"] = 6;
var exception = Assert.Throws<HttpResponseException>(
() => actionDescriptor.ExecuteAsync(_context, _arguments).RethrowFaultedTaskException());
Assert.Equal(HttpStatusCode.BadRequest, exception.Response.StatusCode);
var content = Assert.IsType<ObjectContent<string>>(exception.Response.Content);
Assert.Equal("The parameters dictionary does not contain an entry for parameter 'id' of type 'System.Int32' " +
"for method 'System.Web.Http.User RetriveUser(Int32)' in 'System.Web.Http.UsersRpcController'. " +
"The dictionary must contain an entry for each parameter, including parameters that have null values.",
content.Value);
}
[Fact]
public void ExecuteAsync_Throws_IfArgumentTypeIsWrong()
{
Func<int, User> retrieveUserMethod = _controller.RetriveUser;
ReflectedHttpActionDescriptor actionDescriptor = new ReflectedHttpActionDescriptor { MethodInfo = retrieveUserMethod.Method };
_arguments["id"] = new DateTime();
var exception = Assert.Throws<HttpResponseException>(
() => actionDescriptor.ExecuteAsync(_context, _arguments).RethrowFaultedTaskException());
Assert.Equal(HttpStatusCode.BadRequest, exception.Response.StatusCode);
var content = Assert.IsType<ObjectContent<string>>(exception.Response.Content);
Assert.Equal("The parameters dictionary contains an invalid entry for parameter 'id' for method " +
"'System.Web.Http.User RetriveUser(Int32)' in 'System.Web.Http.UsersRpcController'. " +
"The dictionary contains a value of type 'System.DateTime', but the parameter requires a value " +
"of type 'System.Int32'.",
content.Value);
}
[Fact]
public void ExecuteAsync_IfTaskReturningMethod_ReturnsWrappedTaskInstance_Throws()
{
Func<Task> method = _controller.WrappedTaskReturningMethod;
ReflectedHttpActionDescriptor actionDescriptor = new ReflectedHttpActionDescriptor { MethodInfo = method.Method };
var exception = Assert.Throws<InvalidOperationException>(
() => actionDescriptor.ExecuteAsync(_context, _arguments).RethrowFaultedTaskException(),
"The method 'WrappedTaskReturningMethod' on type 'UsersRpcController' returned an instance of 'System.Threading.Tasks.Task`1[[System.Threading.Tasks.Task, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]]'. Make sure to call Unwrap on the returned value to avoid unobserved faulted Task.");
}
[Fact]
public void ExecuteAsync_IfObjectReturningMethod_ReturnsTaskInstance_Throws()
{
Func<object> method = _controller.TaskAsObjectReturningMethod;
ReflectedHttpActionDescriptor actionDescriptor = new ReflectedHttpActionDescriptor { MethodInfo = method.Method };
var exception = Assert.Throws<InvalidOperationException>(
() => actionDescriptor.ExecuteAsync(_context, _arguments).RethrowFaultedTaskException(),
"The method 'TaskAsObjectReturningMethod' on type 'UsersRpcController' returned a Task instance even though it is not an asynchronous method.");
}
[Theory]
[InlineData(typeof(void), null)]
[InlineData(typeof(string), typeof(string))]
[InlineData(typeof(Task), null)]
[InlineData(typeof(Task<string>), typeof(string))]
public void GetReturnType_ReturnsUnwrappedActionType(Type methodReturnType, Type expectedReturnType)
{
Mock<MethodInfo> methodMock = new Mock<MethodInfo>();
methodMock.Setup(m => m.ReturnType).Returns(methodReturnType);
Assert.Equal(expectedReturnType, ReflectedHttpActionDescriptor.GetReturnType(methodMock.Object));
}
}
}

View File

@ -0,0 +1,93 @@
// Copyright (c) Microsoft Corporation. All rights reserved. See License.txt in the project root for license information.
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Web.Http.Controllers;
using Moq;
using Xunit;
using Assert = Microsoft.TestCommon.AssertEx;
namespace System.Web.Http
{
public class ReflectedHttpParameterDescriptorTest
{
[Fact]
public void Parameter_Constructor()
{
UsersRpcController controller = new UsersRpcController();
Func<string, string, User> echoUserMethod = controller.EchoUser;
ReflectedHttpActionDescriptor actionDescriptor = new ReflectedHttpActionDescriptor { MethodInfo = echoUserMethod.Method };
ParameterInfo parameterInfo = echoUserMethod.Method.GetParameters()[0];
ReflectedHttpParameterDescriptor parameterDescriptor = new ReflectedHttpParameterDescriptor(actionDescriptor, parameterInfo);
Assert.Equal(actionDescriptor, parameterDescriptor.ActionDescriptor);
Assert.Null(parameterDescriptor.DefaultValue);
Assert.Equal(parameterInfo, parameterDescriptor.ParameterInfo);
Assert.Equal(parameterInfo.Name, parameterDescriptor.ParameterName);
Assert.Equal(typeof(string), parameterDescriptor.ParameterType);
Assert.Null(parameterDescriptor.Prefix);
Assert.Null(parameterDescriptor.ModelBinderAttribute);
}
[Fact]
public void Constructor_Throws_IfParameterInfoIsNull()
{
Assert.ThrowsArgumentNull(
() => new ReflectedHttpParameterDescriptor(new Mock<HttpActionDescriptor>().Object, null),
"parameterInfo");
}
[Fact]
public void Constructor_Throws_IfActionDescriptorIsNull()
{
Assert.ThrowsArgumentNull(
() => new ReflectedHttpParameterDescriptor(null, new Mock<ParameterInfo>().Object),
"actionDescriptor");
}
[Fact]
public void ParameterInfo_Property()
{
ParameterInfo referenceParameter = new Mock<ParameterInfo>().Object;
Assert.Reflection.Property(new ReflectedHttpParameterDescriptor(), d => d.ParameterInfo, expectedDefaultValue: null, allowNull: false, roundTripTestValue: referenceParameter);
}
[Fact]
public void IsDefined_Retruns_True_WhenParameterAttributeIsFound()
{
UsersRpcController controller = new UsersRpcController();
Action<User> addUserMethod = controller.AddUser;
ReflectedHttpActionDescriptor actionDescriptor = new ReflectedHttpActionDescriptor { MethodInfo = addUserMethod.Method };
ParameterInfo parameterInfo = addUserMethod.Method.GetParameters()[0];
ReflectedHttpParameterDescriptor parameterDescriptor = new ReflectedHttpParameterDescriptor(actionDescriptor, parameterInfo);
}
[Fact]
public void GetCustomAttributes_Returns_ParameterAttributes()
{
UsersRpcController controller = new UsersRpcController();
Action<User> addUserMethod = controller.AddUser;
ReflectedHttpActionDescriptor actionDescriptor = new ReflectedHttpActionDescriptor { MethodInfo = addUserMethod.Method };
ParameterInfo parameterInfo = addUserMethod.Method.GetParameters()[0];
ReflectedHttpParameterDescriptor parameterDescriptor = new ReflectedHttpParameterDescriptor(actionDescriptor, parameterInfo);
object[] attributes = parameterDescriptor.GetCustomAttributes<object>().ToArray();
Assert.Equal(1, attributes.Length);
Assert.Equal(typeof(FromBodyAttribute), attributes[0].GetType());
}
[Fact]
public void GetCustomAttributes_AttributeType_Returns_ParameterAttributes()
{
UsersRpcController controller = new UsersRpcController();
Action<User> addUserMethod = controller.AddUser;
ReflectedHttpActionDescriptor actionDescriptor = new ReflectedHttpActionDescriptor { MethodInfo = addUserMethod.Method };
ParameterInfo parameterInfo = addUserMethod.Method.GetParameters()[0];
ReflectedHttpParameterDescriptor parameterDescriptor = new ReflectedHttpParameterDescriptor(actionDescriptor, parameterInfo);
IEnumerable<FromBodyAttribute> attributes = parameterDescriptor.GetCustomAttributes<FromBodyAttribute>();
Assert.Equal(1, attributes.Count());
}
}
}

View File

@ -0,0 +1,52 @@
// Copyright (c) Microsoft Corporation. All rights reserved. See License.txt in the project root for license information.
using System.Net.Http;
using Xunit;
using Assert = Microsoft.TestCommon.AssertEx;
namespace System.Web.Http.Controllers
{
public class ResponseMessageResultConverterTest
{
private readonly ResponseMessageResultConverter _converter = new ResponseMessageResultConverter();
private readonly HttpControllerContext _context = new HttpControllerContext();
private readonly HttpRequestMessage _request = new HttpRequestMessage();
public ResponseMessageResultConverterTest()
{
_context.Request = _request;
_context.Configuration = new HttpConfiguration();
}
[Fact]
public void Convert_WhenValueIsResponseMessage_ReturnsResponseMessageWithRequestAssigned()
{
HttpResponseMessage response = new HttpResponseMessage();
var result = _converter.Convert(_context, response);
Assert.Same(response, result);
Assert.Same(_request, result.RequestMessage);
}
[Fact]
public void Convert_WhenContextIsNull_Throws()
{
Assert.ThrowsArgumentNull(() => _converter.Convert(controllerContext: null, actionResult: new HttpResponseMessage()), "controllerContext");
}
[Fact]
public void Convert_WhenValueIsNull_Throws()
{
Assert.Throws<InvalidOperationException>(() => _converter.Convert(_context, null),
"A null value was returned where an instance of HttpResponseMessage was expected.");
}
[Fact]
public void Convert_WhenValueIsIncompatibleType_Throws()
{
Assert.Throws<InvalidCastException>(() => _converter.Convert(_context, "42"),
"Unable to cast object of type 'System.String' to type 'System.Net.Http.HttpResponseMessage'.");
}
}
}

View File

@ -0,0 +1,68 @@
// Copyright (c) Microsoft Corporation. All rights reserved. See License.txt in the project root for license information.
using System.Net;
using System.Net.Http;
using System.Net.Http.Formatting;
using Xunit;
using Assert = Microsoft.TestCommon.AssertEx;
namespace System.Web.Http.Controllers
{
public class ValueResultConverterTest
{
private readonly ValueResultConverter<object> _objectValueConverter = new ValueResultConverter<object>();
private readonly ValueResultConverter<Animal> _animalValueConverter = new ValueResultConverter<Animal>();
private readonly HttpControllerContext _context = new HttpControllerContext();
private readonly HttpRequestMessage _request = new HttpRequestMessage();
public ValueResultConverterTest()
{
_context.Request = _request;
_context.Configuration = new HttpConfiguration();
}
[Fact]
public void Convert_WhenContextIsNull_Throws()
{
Assert.ThrowsArgumentNull(() => _objectValueConverter.Convert(controllerContext: null, actionResult: new object()), "controllerContext");
}
[Fact]
public void Convert_WhenValueTypeIsNotCompatible_Throws()
{
Assert.Throws<InvalidCastException>(() => _animalValueConverter.Convert(_context, new object()),
"Unable to cast object of type 'System.Object' to type 'Animal'.");
}
[Fact]
public void Convert_WhenValueIsResponseMessage_ReturnsResponseMessageWithRequestAssigned()
{
HttpResponseMessage response = new HttpResponseMessage();
var result = _objectValueConverter.Convert(_context, response);
Assert.Same(response, result);
Assert.Same(_request, result.RequestMessage);
}
[Fact]
public void Convert_WhenValueIsAnyType_CreatesContentNegotiatedResponse()
{
Dog dog = new Dog();
XmlMediaTypeFormatter formatter = new XmlMediaTypeFormatter();
_context.Configuration.Formatters.Clear();
_context.Configuration.Formatters.Add(formatter);
var result = _animalValueConverter.Convert(_context, dog);
Assert.Equal(HttpStatusCode.OK, result.StatusCode);
var content = Assert.IsType<ObjectContent<Animal>>(result.Content);
Assert.Same(dog, content.Value);
Assert.Same(formatter, content.Formatter);
Assert.Same(_request, result.RequestMessage);
}
public class Animal { }
public class Dog : Animal { }
}
}

View File

@ -0,0 +1,38 @@
// Copyright (c) Microsoft Corporation. All rights reserved. See License.txt in the project root for license information.
using System.Net;
using System.Net.Http;
using Xunit;
using Assert = Microsoft.TestCommon.AssertEx;
namespace System.Web.Http.Controllers
{
public class VoidResultConverterTest
{
private readonly VoidResultConverter _converter = new VoidResultConverter();
private readonly HttpControllerContext _context = new HttpControllerContext();
private readonly HttpRequestMessage _request = new HttpRequestMessage();
public VoidResultConverterTest()
{
_context.Request = _request;
_context.Configuration = new HttpConfiguration();
}
[Fact]
public void Convert_WhenContextIsNull_Throws()
{
Assert.ThrowsArgumentNull(() => _converter.Convert(controllerContext: null, actionResult: null), "controllerContext");
}
[Fact]
public void Convert_ReturnsResponseMessageWithRequestAssigned()
{
var result = _converter.Convert(_context, null);
Assert.Equal(HttpStatusCode.OK, result.StatusCode);
Assert.Null(result.Content);
Assert.Same(_request, result.RequestMessage);
}
}
}