コード例 #1
0
        public void Setting_CustomActionSelector()
        {
            // Arrange
            ApiController api = new UsersController();
            HttpControllerContext controllerContext = ContextUtil.CreateControllerContext();

            HttpControllerDescriptor controllerDescriptor = new HttpControllerDescriptor(controllerContext.Configuration, "test", typeof(UsersController));
            controllerContext.ControllerDescriptor = controllerDescriptor;

            Mock<IHttpActionSelector> mockSelector = new Mock<IHttpActionSelector>();
            mockSelector
                .Setup(invoker => invoker.SelectAction(It.IsAny<HttpControllerContext>()))
                .Returns(() =>
                {
                    Func<HttpResponseMessage> testDelegate =
                        () => new HttpResponseMessage { Content = new StringContent("This is a test") };
                    return new ReflectedHttpActionDescriptor
                    {
                        Configuration = controllerContext.Configuration,
                        ControllerDescriptor = controllerDescriptor,
                        MethodInfo = testDelegate.Method
                    };
                });
            controllerDescriptor.Configuration.Services.Replace(typeof(IHttpActionSelector), mockSelector.Object);

            // Act
            HttpResponseMessage message = api.ExecuteAsync(
                controllerContext,
                CancellationToken.None).Result;

            // Assert
            Assert.Equal("This is a test", message.Content.ReadAsStringAsync().Result);
        }
コード例 #2
0
        public void UsersController_Post_ValidModelStateSavesUser()
        {
            // Arrange

            var repository = Substitute.For<IRepository>();

            var usersController = new UsersController(repository);
            usersController.Request = new HttpRequestMessage();
            usersController.Configuration = new HttpConfiguration();

            // Mock the UrlHelper in order for the controller 
            // to be able to successfully call the Url.Link() method.
            var urlHelper = Substitute.For<UrlHelper>();
            urlHelper.Link(Arg.Any<string>(), Arg.Any<object>()).Returns("http://localhost/api/users/0");
            usersController.Url = urlHelper;

            var viewModel = new UserAddViewModel()
            {
                UserName = "******",
                Password = "******"
            };

            // Act
            var actionResult = usersController.Post(viewModel) as CreatedNegotiatedContentResult<UserMessage>;

            // Assert
            Assert.IsNotNull(actionResult);
            Assert.AreEqual(0, actionResult.Content.UserId);
            Assert.AreEqual("johns", actionResult.Content.UserName);
            repository.ReceivedWithAnyArgs().SaveUser(null);
        }
コード例 #3
0
        public void Setting_CustomActionInvoker()
        {
            // Arrange
            ApiController api = new UsersController();
            string responseText = "Hello World";
            HttpControllerContext controllerContext = ContextUtil.CreateControllerContext();

            HttpControllerDescriptor controllerDescriptor = new HttpControllerDescriptor(controllerContext.Configuration, "test", typeof(UsersController));
            controllerContext.ControllerDescriptor = controllerDescriptor;

            Mock<IHttpActionInvoker> mockInvoker = new Mock<IHttpActionInvoker>();
            mockInvoker
                .Setup(invoker => invoker.InvokeActionAsync(It.IsAny<HttpActionContext>(), It.IsAny<CancellationToken>()))
                .Returns(() =>
                {
                    TaskCompletionSource<HttpResponseMessage> tcs = new TaskCompletionSource<HttpResponseMessage>();
                    tcs.TrySetResult(new HttpResponseMessage() { Content = new StringContent(responseText) });
                    return tcs.Task;
                });
            controllerDescriptor.Configuration.Services.Replace(typeof(IHttpActionInvoker), mockInvoker.Object);

            // Act
            HttpResponseMessage message = api.ExecuteAsync(
                controllerContext,
                CancellationToken.None).Result;

            // Assert
            Assert.Equal(responseText, message.Content.ReadAsStringAsync().Result);
        }
コード例 #4
0
        public void UsersController_Post_NoViewModelReturnsBadRequest()
        {
            // Arrange
            var usersController = new UsersController(null);

            // Act
            var actionResult = usersController.Post(null);

            // Assert
            Assert.IsInstanceOfType(actionResult, typeof(InvalidModelStateResult));
        }
コード例 #5
0
        public void Init()
        {
            _ctrl = new UsersController(new FakeUsersRepository());
            var config = new HttpConfiguration();
            var request = new HttpRequestMessage(HttpMethod.Post, "http://localhost/be/api");
            var route = config.Routes.MapHttpRoute("DefaultApi", "api/{controller}/{id}");
            var routeData = new HttpRouteData(route, new HttpRouteValueDictionary { { "controller", "users" } });

            _ctrl.ControllerContext = new HttpControllerContext(config, routeData, request);
            _ctrl.Request = request;
            _ctrl.Request.Properties[HttpPropertyKeys.HttpConfigurationKey] = config;
        }
コード例 #6
0
        public void Init()
        {
            _ctrl = new UsersController(new FakeRepository());
            path=AppDomain.CurrentDomain.BaseDirectory;
            path = path.Remove(path.Length - @"bin\debug\".Length);
            path= path + "\\config\\serverPath.dat";
            using (StreamReader reader = new StreamReader(path))
            {

                serverPath = reader.ReadLine();
            }

        }
コード例 #7
0
        public void UsersController_Post_InvalidModelStateReturnsErrorRequest()
        {
            // Arrange
            var usersController = new UsersController(null);
            var viewModel = new UserAddViewModel();

            // Add a model state error.
            usersController.ModelState.AddModelError("UserName", "UserName is required.");

            // Act
            var actionResult = usersController.Post(viewModel);

            // Assert
            Assert.IsInstanceOfType(actionResult, typeof(ErrorActionResult));
        }
コード例 #8
0
        public void Setting_CustomActionSelector()
        {
            // Arrange
            ApiController         api = new UsersController();
            HttpControllerContext controllerContext = ContextUtil.CreateControllerContext();

            HttpControllerDescriptor controllerDescriptor = new HttpControllerDescriptor(controllerContext.Configuration, "test", typeof(UsersController));

            controllerContext.ControllerDescriptor = controllerDescriptor;

            Mock <IHttpActionSelector> mockSelector = new Mock <IHttpActionSelector>();

            mockSelector
            .Setup(invoker => invoker.SelectAction(It.IsAny <HttpControllerContext>()))
            .Returns(() =>
            {
                Func <HttpResponseMessage> testDelegate =
                    () => new HttpResponseMessage {
                    Content = new StringContent("This is a test")
                };
                return(new ReflectedHttpActionDescriptor
                {
                    Configuration = controllerContext.Configuration,
                    ControllerDescriptor = controllerDescriptor,
                    MethodInfo = testDelegate.Method
                });
            });
            controllerDescriptor.Configuration.Services.Replace(typeof(IHttpActionSelector), mockSelector.Object);

            // Act
            HttpResponseMessage message = api.ExecuteAsync(
                controllerContext,
                CancellationToken.None).Result;

            // Assert
            Assert.Equal("This is a test", message.Content.ReadAsStringAsync().Result);
        }
コード例 #9
0
        public void Default_Get()
        {
            // Arrange
            ApiController api = new UsersController();
            HttpControllerContext controllerContext = ContextUtil.CreateControllerContext(instance: api, request: new HttpRequestMessage() { Method = HttpMethod.Get });
            controllerContext.ControllerDescriptor = new HttpControllerDescriptor(controllerContext.Configuration, "test", typeof(UsersController));

            // Act
            HttpResponseMessage message = api.ExecuteAsync(
                controllerContext,
                CancellationToken.None).Result;

            // Assert
            Assert.Equal("Default User", message.Content.ReadAsStringAsync().Result);
        }
コード例 #10
0
        public void Invalid_Action_In_Route()
        {
            // Arrange
            ApiController api = new UsersController();
            HttpRouteData route = new HttpRouteData(new HttpRoute());
            string actionName = "invalidOp";
            route.Values.Add("action", actionName);
            HttpControllerContext controllerContext = ContextUtil.CreateControllerContext(instance: api, routeData: route, request: new HttpRequestMessage() { Method = HttpMethod.Get });
            Type controllerType = typeof(UsersController);
            controllerContext.ControllerDescriptor = new HttpControllerDescriptor(controllerContext.Configuration, controllerType.Name, controllerType);
            controllerContext.Configuration.IncludeErrorDetailPolicy = IncludeErrorDetailPolicy.Always;

            // Act & Assert
            var exception = Assert.Throws<HttpResponseException>(() =>
             {
                 HttpResponseMessage message = api.ExecuteAsync(controllerContext, CancellationToken.None).Result;
             });

            Assert.Equal(HttpStatusCode.NotFound, exception.Response.StatusCode);
            var content = Assert.IsType<ObjectContent<HttpError>>(exception.Response.Content);
            Assert.Equal("No action was found on the controller 'UsersController' that matches the name 'invalidOp'.",
                ((HttpError)content.Value)["MessageDetail"]);
        }