public async Task GetWithParamReturnsOkOrNotFound() { //Arrange //Act IHttpActionResult response = await Controller.Get(1); Type respType = response.GetType(); //Assert //TODO: Should actually check for 200 Assert.IsNotInstanceOfType(response.GetType(), typeof(InternalServerErrorResult)); }
public void SaveChatMessage() { ChatMessage channelChatMessage = new ChannelMessage { Channel = new Channel { ChannelName = "test channel" }, Message = "test channel message", Originator = new ChatUser { UserName = "******", UserToken = "12345" } }; Assert.AreEqual(0, this.sessionContext.ChatUsers.Count(), "the chat user list should be empty on start up"); IHttpActionResult result = this.chatMessageController.Save(base.BuildFakeJsonRequestMessage(channelChatMessage)); Assert.AreEqual(1, this.sessionContext.ChatMessages.Count(), "the chat message was not saved"); Assert.AreEqual("test channel", (this.sessionContext.ChatMessages.FirstOrDefault() as ChannelMessage).Channel.ChannelName, "the channel name was incorrect"); Assert.AreEqual("test channel message", this.sessionContext.ChatMessages.FirstOrDefault().Message, "the message was incorrect"); Assert.AreEqual("test user name", this.sessionContext.ChatMessages.FirstOrDefault().Originator.UserName, "the user was incorrect"); Assert.AreEqual("12345", this.sessionContext.ChatMessages.FirstOrDefault().Originator.UserToken, "the user token was incorrect"); Assert.AreEqual(typeof(System.Web.Http.Results.OkResult), result.GetType(), "the result was incorrect"); ChatMessage directMessageToSave = new DirectMessage { To = new ChatUser { UserName = "******", UserToken = "98765" }, Message = "Test channel message", Originator = new ChatUser { UserName = "******", UserToken = "12345" } }; result = this.chatMessageController.Save(base.BuildFakeJsonRequestMessage(directMessageToSave)); Assert.AreEqual(2, this.sessionContext.ChatMessages.Count(), "values were added in error or wiped out!"); Assert.AreEqual("user to", (this.sessionContext.ChatMessages.LastOrDefault() as DirectMessage).To.UserName, "the user to send to was incorrect"); Assert.AreEqual("98765", (this.sessionContext.ChatMessages.LastOrDefault() as DirectMessage).To.UserToken, "the user to send to token was incorrect"); Assert.AreEqual("Test channel message", this.sessionContext.ChatMessages.LastOrDefault().Message, "the message was incorrect"); Assert.AreEqual("test user", this.sessionContext.ChatMessages.LastOrDefault().Originator.UserName, "the user was incorrect"); Assert.AreEqual("12345", this.sessionContext.ChatMessages.LastOrDefault().Originator.UserToken, "the user token was incorrect"); Assert.AreEqual(typeof(System.Web.Http.Results.OkResult), result.GetType(), "the result was incorrect"); }
public async Task Get_WhenGettingAllQuestions_ThenReturnListOfQuestions() { QuestionPagedItem[] questionItems = new QuestionPagedItem[] { new QuestionPagedItem { ID = Guid.NewGuid(), Number = 1, Section = "Section 1" }, new QuestionPagedItem { ID = Guid.NewGuid(), Number = 2, Section = "Section 2" } }; QuestionPaged questionsPaged = new QuestionPaged { Items = questionItems, TotalCount = questionItems.Length }; questionController.Request = new HttpRequestMessage(HttpMethod.Get, "api/Question/?itemsPerPage=2&pageNumber=1"); questionController.Configuration = new HttpConfiguration(); questionServiceMock.Setup(x => x.GetQuestionsByPageAsync(2, 1)).Returns(Task.FromResult(questionsPaged.DeepCopyTo <Qubiz.QuizEngine.Services.Models.PagedResult <Qubiz.QuizEngine.Services.Models.QuestionListItem> >())); IHttpActionResult actionResult = await questionController.Get(2, 1); QuestionPaged response = (actionResult as OkNegotiatedContentResult <QuestionPaged>).Content; Assert.AreEqual(typeof(OkNegotiatedContentResult <QuestionPaged>), actionResult.GetType()); AssertAreEqual(questionsPaged.Items[0], response.Items[0]); AssertAreEqual(questionsPaged.Items[1], response.Items[1]); Assert.AreEqual(questionsPaged.TotalCount, response.TotalCount); }
protected void AssertStatusCodeResult(IHttpActionResult actionResult, HttpStatusCode expectedStatusCode) { Assert.IsTrue(actionResult.GetType() == typeof(StatusCodeResult)); var response = (StatusCodeResult)actionResult; Assert.AreEqual(expectedStatusCode, response.StatusCode); }
public void SaveOrder_Returns_CreatedNegotiatedContent() { OrdersController ordersController = new OrdersController(this.ordersRepository, this.ordersWriteRepository, this.orderValidation); Order newOrder = new Order { OrderNumber = "YN50-2315", CustomerId = "Customer1", OrderDate = new DateTime(2016, 06, 15), OrderItems = new[] { new OrderItem { ItemName = "Book", Amount = 20 }, new OrderItem { ItemName = "Card", Amount = 10 }, new OrderItem { ItemName = "Pen", Amount = 5 } } }; IHttpActionResult actionResult = ordersController.Save(newOrder.OrderNumber, newOrder.CustomerId, new DateTime(2016, 06, 23), newOrder.OrderItems); Assert.IsTrue(actionResult.GetType() == typeof(CreatedNegotiatedContentResult <Order>)); }
public void SaveOrderNoCustomerId_Returns_BadRequest() { OrdersController ordersController = new OrdersController(this.ordersRepository, this.ordersWriteRepository, this.orderValidation); Order newOrder = new Order { OrderNumber = "YN00-0000", CustomerId = "Customer1", OrderDate = new DateTime(2016, 06, 15), OrderItems = new[] { new OrderItem { ItemName = "Book", Amount = 20 }, new OrderItem { ItemName = "Card", Amount = 10 }, new OrderItem { ItemName = "Pen", Amount = 5 } } }; IHttpActionResult actionResult = ordersController.Save(newOrder.OrderNumber, "", DateTime.Now, newOrder.OrderItems); Assert.IsTrue(actionResult.GetType() == typeof(BadRequestResult)); }
public async Task Post_WhenAddingQuestion_ThenOkStatusCodeIsReturned() { Guid questionID = Guid.NewGuid(); Option[] options = new Option[] { new Option { ID = Guid.NewGuid(), Answer = "This is a test", IsCorrectAnswer = true, Order = 1, QuestionID = questionID }, new Option { ID = Guid.NewGuid(), Answer = "This is a test 2", IsCorrectAnswer = false, Order = 2, QuestionID = questionID }, }; Question question = new Question { ID = questionID, Complexity = 1, Number = 1, QuestionText = "This is a test", SectionID = Guid.NewGuid(), Type = QuestionType.SingleSelect, Options = options }; questionController.Request = new HttpRequestMessage(HttpMethod.Post, "api/Question/"); questionController.Configuration = new HttpConfiguration(); questionServiceMock.Setup(x => x.AddQuestionAsync(It.Is <Qubiz.QuizEngine.Services.Models.QuestionDetail>(s => (HaveEqualState(s, question))))).Returns(Task.CompletedTask); IHttpActionResult actionResult = await questionController.Post(question.DeepCopyTo <Question>()); Assert.AreEqual(typeof(OkResult), actionResult.GetType()); }
public void ReadOrder_Returns_NotFound() { OrdersController ordersController = new OrdersController(this.ordersRepository, this.ordersWriteRepository, this.orderValidation); this.ordersRepository.Read().Returns(new List <Order> { new Order { OrderNumber = "YN50-2315", CustomerId = "Customer1", OrderDate = new DateTime(2016, 06, 15), OrderItems = new[] { new OrderItem { ItemName = "Book", Amount = 20 }, new OrderItem { ItemName = "Card", Amount = 10 }, new OrderItem { ItemName = "Pen", Amount = 5 } } }, new Order { OrderNumber = "YN88-2005", CustomerId = "Customer1", OrderDate = new DateTime(2016, 04, 02), OrderItems = new[] { new OrderItem { ItemName = "Book", Amount = 20 }, new OrderItem { ItemName = "Card", Amount = 10 }, new OrderItem { ItemName = "Pen", Amount = 5 } } } }.AsQueryable()); IHttpActionResult actionResult = ordersController.ReadOrder("YN88-4859"); Assert.IsTrue(actionResult.GetType() == typeof(NotFoundResult)); }
public void ReturnOKResultWhenPostWithMultipleValidModels() { AssumeModelValidationForPostPasses(); IHttpActionResult result = AssumePost(SetupListToPost(3)); _ = result.GetType().Should().Be(typeof(OkResult), "OK response expected."); }
public void ReturnBadRequestResultWhenPostWithMultipleInValidModels() { AssumeModelValidationForPostFails(); IHttpActionResult result = AssumePost(SetupListToPost(3)); _ = result.GetType().Should().Be(typeof(ResponseMessageResult), "ResponseMessageResult expected with bad request reason"); }
public async Task Get_WhenGettingQuestionByID_ThenReturnQuestionByID() { Guid questionID = Guid.NewGuid(); Option[] options = new Option[] { new Option { ID = Guid.NewGuid(), Answer = "This is a test", IsCorrectAnswer = true, Order = 1, QuestionID = questionID }, new Option { ID = Guid.NewGuid(), Answer = "This is a test 2", IsCorrectAnswer = false, Order = 2, QuestionID = questionID }, }; Question question = new Question { ID = questionID, Complexity = 1, Number = 1, QuestionText = "This is a test", SectionID = Guid.NewGuid(), Type = QuestionType.SingleSelect, Options = options }; questionController.Request = new HttpRequestMessage(HttpMethod.Get, "api/Question/?" + question.ID); questionController.Configuration = new HttpConfiguration(); questionServiceMock.Setup(x => x.GetQuestionByID(question.ID)).Returns(Task.FromResult(question.DeepCopyTo <Qubiz.QuizEngine.Services.Models.QuestionDetail>())); IHttpActionResult actionResult = await questionController.Get(question.ID); Question response = (actionResult as OkNegotiatedContentResult <Question>).Content; Assert.AreEqual(typeof(OkNegotiatedContentResult <Question>), actionResult.GetType()); AssertAreEqual(question, response); AssertAreEqual(question.Options[0], response.Options[0]); AssertAreEqual(question.Options[1], question.Options[1]); }
public void GetPhoneBookList_Null_Test() { var controller = new PhoneBookController(); IHttpActionResult actionResult = controller.GetPhoneBookList(""); var type = actionResult.GetType(); var expectedType = typeof(BadRequestErrorMessageResult); Assert.AreEqual(type.Name, expectedType.Name); }
public static bool IsSuccessfulResponse(this IHttpActionResult result) { var t = result.GetType(); var genTypes = new[] { typeof(OkNegotiatedContentResult <>), typeof(CreatedAtRouteNegotiatedContentResult <>), typeof(CreatedNegotiatedContentResult <>) }; return((result is OkResult) || (result is StatusCodeResult && ((int)((StatusCodeResult)(result)).StatusCode).ToString().StartsWith("20")) || (t.IsGenericType && genTypes.Any(x => t.GetGenericTypeDefinition().IsAssignableFrom(x)))); }
public static T ExpectOkNegotiatedContentResult <T>(this IHttpActionResult actionResult) { var negotiatedContentResult = actionResult as OkNegotiatedContentResult <T>; if (negotiatedContentResult != null) { return(negotiatedContentResult.Content); } throw new ArgumentException(string.Format("The argument is not of type OkNegotiatedContentResult<{0}>. Got {1} instead.", typeof(T).FullName, actionResult.GetType().FullName), "actionResult"); }
public static QueryResult <T> ExpectQueryResult <T>(this IHttpActionResult actionResult) { var queryResult = actionResult as QueryResult <T>; if (queryResult != null) { return(queryResult); } throw new ArgumentException(string.Format("The argument is not of type QueryResult<{0}>. Got {1} instead.", typeof(T).FullName, actionResult.GetType().FullName), "actionResult"); }
private THttpActionResult AssertHttpActionResult <THttpActionResult>(IHttpActionResult actionResult) where THttpActionResult : IHttpActionResult { Type expectedType = typeof(THttpActionResult); if (actionResult == null || !TypeTester.IsOfType(actionResult, expectedType)) { string actualTypeName = (actionResult == null) ? "null" : actionResult.GetType().FullName; throw new ControllerTestException($"Expected IHttpActionResult type {expectedType.FullName}. Actual: {actualTypeName}."); } return((THttpActionResult)actionResult); }
public async Task ConfirmReturnsNoContent() { //Arrange //Act IHttpActionResult response = await Controller.Confirm(1); //Assert //TODO: Should actually check for 201 Assert.IsNotInstanceOfType(response.GetType(), typeof(InternalServerErrorResult)); }
public async Task Delete_WhenDeletingQuestion_ThenOkStatusCodeIsReturned() { Guid questionID = Guid.NewGuid(); questionController.Request = new HttpRequestMessage(HttpMethod.Delete, "api/Question/"); questionController.Configuration = new HttpConfiguration(); questionServiceMock.Setup(x => x.DeleteQuestionAsync(questionID)).Returns(Task.CompletedTask); IHttpActionResult actionResult = await questionController.Delete(questionID); Assert.AreEqual(typeof(OkResult), actionResult.GetType()); }
public void SaveChatUser() { ChatUser user = new ChatUser { UserName = "******", UserToken = "12345" }; Assert.AreEqual(0, this.sessionContext.ChatUsers.Count(), "the chat user list should be empty on start up"); IHttpActionResult result = this.chatUserController.Save(user); Assert.AreEqual(2, this.sessionContext.ChatUsers.Count(), "the chatuser list was not updated"); Assert.AreEqual("test user", this.sessionContext.ChatUsers.FirstOrDefault().UserName, "the chatuser name was incorrect"); Assert.AreEqual("12345", this.sessionContext.ChatUsers.FirstOrDefault().UserToken, "the chatuser token was incorrect"); Assert.AreEqual(typeof(System.Web.Http.Results.OkResult), result.GetType(), "the result was incorrect"); }
public async Task Get_WhenNoQuestionMatchTheSearch_ThenReturnNull() { Guid questionId = Guid.NewGuid(); questionController.Request = new HttpRequestMessage(HttpMethod.Get, "api/Question/?" + questionId); questionController.Configuration = new HttpConfiguration(); questionServiceMock.Setup(x => x.GetQuestionByID(questionId)).Returns(Task.FromResult((Qubiz.QuizEngine.Services.Models.QuestionDetail)null)); IHttpActionResult actionResult = await questionController.Get(questionId); Question response = (actionResult as OkNegotiatedContentResult <Question>).Content; Assert.AreEqual(typeof(OkNegotiatedContentResult <Question>), actionResult.GetType()); Assert.IsNull(response); }
public async Task <IHttpActionResult> RegisterEmployer(RegisterEmployerBindingModel model) { // Adding one day because of the bug with the Daylight Saving Time model.DateOfBirth = model.DateOfBirth.AddDays(1); if (!ModelState.IsValid) { return(BadRequest(ModelState)); } RegisterUserBindingModel employerToUserBM = AutoMapper.Mapper.Map <RegisterUserBindingModel>(model); IHttpActionResult resultOfUserRegistering = await this.Register(employerToUserBM); if (typeof(OkNegotiatedContentResult <string>) != resultOfUserRegistering.GetType()) { return(resultOfUserRegistering); } var userId = (resultOfUserRegistering as OkNegotiatedContentResult <string>).Content; User user = await _context.Users.FirstOrDefaultAsync(u => u.Id == userId); var rolesForEmployer = new[] { "Employer" }; var resultOfAddingToRoles = await SafelyAddUserToRole(rolesForEmployer, user.Id); if (resultOfAddingToRoles == false) { return(InternalServerError(new Exception("Adding user to role failed."))); } try { Employer newEmployer = AutoMapper.Mapper.Map <RegisterEmployerBindingModel, Employer>(model); newEmployer.User = user; newEmployer.UserId = user.Id; _context.Employers.Add(newEmployer); _context.SaveChanges(); } catch (Exception e) { Console.WriteLine(e); throw; } return(Ok()); }
public void UnitTestGetAsync() { UserController userController = ProbarResolucion <UserController>(); userController.Request = new System.Net.Http.HttpRequestMessage(); userController.Configuration = new System.Web.Http.HttpConfiguration(); var llamada = Task.Run(() => userController.Get(Guid.Parse("946c2551-779a-4dfd-a539-23bf19719a16"))); llamada.Wait(); IHttpActionResult response = llamada.Result; Assert.IsTrue(response.GetType() == typeof(OkNegotiatedContentResult <UserModel>)); UserModel user = ((OkNegotiatedContentResult <UserModel>)response).Content; Assert.IsNotNull(user); }
public void UnitTestGetAllAsync() { UserController userController = ProbarResolucion <UserController>(); userController.Request = new System.Net.Http.HttpRequestMessage(); userController.Configuration = new System.Web.Http.HttpConfiguration(); var llamada = Task.Run(() => userController.Get()); llamada.Wait(); IHttpActionResult response = llamada.Result; Assert.IsTrue(response.GetType() == typeof(OkNegotiatedContentResult <IEnumerable <UserModel> >)); IEnumerable <UserModel> users = ((OkNegotiatedContentResult <IEnumerable <UserModel> >)response).Content; Assert.IsTrue(users.Any()); }
public async Task Get_WhenNoQuestionsMatchTheSearch_ThenNoQuestionsAreReturned() { QuestionPaged questions = new QuestionPaged(); questionController.Request = new HttpRequestMessage(HttpMethod.Get, "api/Question/?itemsPerPage=2&pageNumber=1"); questionController.Configuration = new HttpConfiguration(); questionServiceMock.Setup(x => x.GetQuestionsByPageAsync(2, 1)).Returns(Task.FromResult(questions.DeepCopyTo <Qubiz.QuizEngine.Services.Models.PagedResult <Qubiz.QuizEngine.Services.Models.QuestionListItem> >())); IHttpActionResult actionResult = await questionController.Get(2, 1); QuestionPaged response = (actionResult as OkNegotiatedContentResult <QuestionPaged>).Content; Assert.AreEqual(typeof(OkNegotiatedContentResult <QuestionPaged>), actionResult.GetType()); Assert.AreEqual(0, response.Items.Length); Assert.AreEqual(0, response.TotalCount); }
public async Task AddMatchReturnsCreated() { //Arrange //Act IHttpActionResult response = await Controller.Post(new AddUpdateMatchModel() { LocationTitle = "TestMatch", LocationMapUrl = "TestMatchMapUrl", MatchDate = DateTime.Now, PlayerLimit = 10 }); //Assert //TODO: Should actually check for 201 Assert.IsNotInstanceOfType(response.GetType(), typeof(InternalServerErrorResult)); }
public async Task SignUpReturnsNoContent() { //Arrange //Act IHttpActionResult response = await Controller.SignUp(new PlayerToMatchModel() { MatchId = 1, SubscriptionDate = DateTime.Now, //TODO: Should seed Admin and use that user UserName = "******" }); //Assert //TODO: Should actually check for either 400 or 201 Assert.IsNotInstanceOfType(response.GetType(), typeof(InternalServerErrorResult)); }
public IHttpActionResult PostTeacher(Teacher teacher) { IHttpActionResult result = SaveItem(teacher); if (result.GetType() == typeof(System.Web.Http.Results.OkResult)) { if (!BusinessLayer.SaveTeacherClassAccesses(teacher)) { return(InternalServerError()); } } else { return(InternalServerError()); } return(Ok()); }
public void SaveChannel() { Channel channel = new Channel { ChannelName = "test channel", Subscribers = new List <ChatUser> { new ChatUser { UserName = "******" } } }; Assert.AreEqual(0, this.sessionContext.Channels.Count(), "the channel list should be empty on start up"); IHttpActionResult result = this.channelController.Save(channel); Assert.AreEqual(1, this.sessionContext.Channels.Count(), "the chat channel list was not updated"); Assert.AreEqual("new user", this.sessionContext.Channels.FirstOrDefault().Subscribers.FirstOrDefault().UserName, "a new channel should be auto subscribed by the initial user"); Assert.AreEqual("test channel", this.sessionContext.Channels.FirstOrDefault().ChannelName, "the channel name was incorrect"); Assert.AreEqual(typeof(System.Web.Http.Results.OkResult), result.GetType(), "the result was incorrect"); }
public void TestCallingGETReturnNotFoundErrorMessageResult() { // Arrange mapsController testObj = new mapsController(mapsControllerTestsUtilities.GetMapNode1Node2CampusCache()); testObj.Request = new HttpRequestMessage(); testObj.ControllerContext.Configuration = new HttpConfiguration(); // Action IHttpActionResult actionResultMap = testObj.Get("mapxxx", "node1", "node2"); IHttpActionResult actionResultNode1 = testObj.Get("map", "node1xxx", "node2"); IHttpActionResult actionResultNode2 = testObj.Get("map", "node1", "node2xxx"); HttpResponseMessage actionResultMapSanityCheck = testObj.Get("map", "node1", "node2").ExecuteAsync(System.Threading.CancellationToken.None).Result; // Assert Assert.AreEqual(typeof(System.Web.Http.Results.NotFoundResult), actionResultMap.GetType()); Assert.AreEqual(typeof(System.Web.Http.Results.NotFoundResult), actionResultNode1.GetType()); Assert.AreEqual(typeof(System.Web.Http.Results.NotFoundResult), actionResultNode2.GetType()); Assert.AreEqual(System.Net.HttpStatusCode.OK, actionResultMapSanityCheck.StatusCode); //Checking that NotFoundResult isnt always returned }
public static TExpectedResultType ExpectResult <TExpectedResultType>(this IHttpActionResult actionResult) where TExpectedResultType : IHttpActionResult { try { return((TExpectedResultType)actionResult); } catch { throw new ArgumentException(string.Format("The argument is not of type {0}. Got {1} instead.", typeof(TExpectedResultType).FullName, actionResult.GetType().FullName), "actionResult"); } }