public void GetTest() { var controller = new ToDoController { Request = new HttpRequestMessage(), Configuration = new HttpConfiguration() }; IHttpActionResult result = controller.Get(); Assert.IsInstanceOfType(result, typeof(OkNegotiatedContentResult<ToDoEntry[]>)); }
public async Task PutSuccessful() { //Arrange var controller = new ToDoController(new ToDoBL(new ToDoRepository())); controller.Request = new HttpRequestMessage { Method = HttpMethod.Put }; controller.Request.Headers.Add("ZUMO-API-VERSION", "2.0.0"); controller.Configuration = new HttpConfiguration(); controller.Configuration.Routes.MapHttpRoute( name: "DefaultApi", routeTemplate: "api/{controller}/{id}", defaults: new { id = RouteParameter.Optional }); controller.RequestContext.RouteData = new HttpRouteData( route: new HttpRoute(), values: new HttpRouteValueDictionary { { "controller", "ToDo" } }); var toDoItems = await controller.Get(); var results = toDoItems.Content.ReadAsAsync <System.Collections.Generic.List <Domain.Models.ToDoItem> >().Result; if (results != null && results.Count > 0) { string id = results[results.Count - 1].Id; ToDoItem request = new ToDoItem() { Id = id, Name = "Test Data for Azure " + id }; //Actual var response = await controller.Put(request); //Assert Assert.IsNotNull(response); Assert.IsNotNull(response.Content); Assert.IsTrue(response.IsSuccessStatusCode); Assert.AreEqual(HttpStatusCode.Accepted, response.StatusCode); } else { Assert.IsTrue(true); } }
public void DeleteEventDeleteObject() { int eventId = 1; var boardMock = new Mock <IStore <Board> >(); var listMock = new Mock <IStore <List> >(); var eventMock = new Mock <IStore <Event> >(); eventMock.Setup(store => store.Delete(eventId)); var userStoreMock = new Mock <IUserStore <ApplicationUser> >(); var userMock = new Mock <UserManager <ApplicationUser> >( userStoreMock.Object, null, null, null, null, null, null, null, null); ToDoController controller = new ToDoController(listMock.Object, userMock.Object, eventMock.Object, boardMock.Object); controller.DeleteEvent(eventId); eventMock.Verify(store => store.Delete(eventId)); }
public async Task GetShouldReturnAllItems() { //Arrange var controller = new ToDoController(new ToDoBL(new ToDoRepository())); controller.Request = new HttpRequestMessage { Method = HttpMethod.Get }; //Actual var response = await controller.Get(); //Assert Assert.IsNotNull(response); Assert.IsNotNull(response.Content); Assert.IsTrue(response.IsSuccessStatusCode); Assert.AreEqual(HttpStatusCode.OK, response.StatusCode); }
public async Task getToDoItems_whenItemsExists_returnAll() { //Arrange _moqRepo.Setup(repo => repo.GetAllItems()) .ReturnsAsync(_toDo); var controller = new ToDoController(_moqRepo.Object); //Act var result = await controller.GetTodoItems(); //Assert Assert.AreEqual(_toDo.Count, result.Count()); Enumerable .Range(0, _toDo.Count) .ToList() .ForEach(i => { Assert.AreEqual(_toDo, result); }); }
public void TestToDoCreateException() { using (var mock = new ToDoMockService()) { // Arrange using (ToDoController controller = new ToDoController(mock)) { // Act ToDoItem item = new ToDoItem(); item.Name = "Test data"; var result = controller.Create(item); //Assert Assert.IsTrue(result.Data.ToString() == "error", "Exception occur so error."); } } }
public void TestToDoUpdateFalseCheck() { // Arrange using (var mockData = new ToDoMockDataService()) { using (ToDoController controller = new ToDoController(mockData)) { // Act ToDoItem item = new ToDoItem(); item.Id = 10; item.Name = "Test data"; var result = controller.Update(item); //Assert Assert.IsTrue(result.Data.ToString() == "error", "Exception occur so error."); } } }
public void TestToDoIndex() { // Arrange using (var repository = new ToDoRepository()) { using (var businessLogic = new ToDoBL(repository, new DataCache())) { using (ToDoController controller = new ToDoController(businessLogic)) { // Act ViewResult result = controller.Index() as ViewResult; // Assert Assert.IsNotNull(result); } } } }
public void GetAllException() { //Arrange var controller = new ToDoController(new ToDoMockService()); controller.Request = new HttpRequestMessage { Method = HttpMethod.Get, }; //Actual var response = controller.Get(); //Assert Assert.IsNotNull(response); Assert.IsNull(response.Content); Assert.AreEqual(HttpStatusCode.InternalServerError, response.StatusCode); }
public async Task TestCreateAccurateData() { // Arrange ToDoController controller = new ToDoController(new ToDoBL(new ToDoRepository(), new DataCache())); // Act ToDoItem item = new ToDoItem(); item.Name = "Test item"; var result = await controller.Create(item); var data = result.Data.GetType().GetProperty("data"); var dataVal = (ToDoItem)data.GetValue(result.Data, null); //Assert Assert.IsTrue(dataVal.Id != null, "Successfully created, ToDo Id retrived:" + dataVal.Id); }
public void TestDeleteWrongId() { // Arrange using (var repository = new ToDoRepository()) { using (var businessLogic = new ToDoBL(repository)) { using (ToDoController controller = new ToDoController(businessLogic)) { // Act controller.ModelState.AddModelError("test", "test"); var result = controller.Delete(45); //Assert Assert.IsTrue(result.Data.ToString() == "error", "Since the id is not present so throwing error."); } } } }
public async Task DeleteException() { //Arrange var controller = new ToDoController(new ToDoMockService()); controller.Request = new HttpRequestMessage { Method = HttpMethod.Delete }; //Actual string id = "0"; var response = await controller.Delete(id); //Assert Assert.IsNotNull(response); Assert.IsNull(response.Content); Assert.AreEqual(HttpStatusCode.InternalServerError, response.StatusCode); }
public async Task CreateorUpdate_Success(ToDoItem item) { //arrange Mock <IToDoService> mockService = new Mock <IToDoService>(); mockService.Setup(x => x.CreateOrUpdate(It.IsAny <ToDoItem>())).Returns(Task.FromResult(1)); var controller = new ToDoController(mockService.Object); //act var returnVal = await controller.CreateOrUpdate(item); var result = returnVal as OkObjectResult; //assert mockService.Verify(x => x.CreateOrUpdate(It.IsAny <ToDoItem>()), Times.Exactly(1)); Assert.NotNull(result); Assert.NotEqual <int>(item.Id, (int)result.Value); }
public async Task GetUserToDoCacheThreeHundredFourResponse() { //Arrange var expected = StatusCodes.Status304NotModified; var mockCache = new Mock <IETagCache>(); mockCache.Setup( cache => cache.GetCachedObject <ToDoDTO>($"todo-{toDoId}") ).Returns(_toDoDTO); //Act var controller = new ToDoController(new Mock <IToDoService>().Object, _mockLogger, mockCache.Object); var result = await controller.Get(userId, toDoId) as StatusCodeResult; //Assert Assert.IsNotNull(result); Assert.IsInstanceOf <StatusCodeResult>(result); Assert.AreEqual(expected, result.StatusCode); }
public void Test_PutToDo_Id_Different() { Mock <ITodoRepository> mockRepository = new Mock <ITodoRepository>(); mockRepository.Setup(mr => mr.save(It.IsAny <ToDo>())).Returns(1); ToDoController tc = new ToDoController(mockRepository.Object); ToDo toDoITem = new ToDo { SlNo = 2, Item = "Edit Test", Description = "Test the Put api" }; TodoResponse apiToDoResponse = tc.PutToDo(0, toDoITem); // If edit took place, header will have success message Assert.AreEqual(apiToDoResponse.responseHeader.statusMessage, AppConstants.Error); Assert.AreEqual(apiToDoResponse.responseHeader.statusCode, HttpStatusCode.BadRequest); }
public void PostBoardAddBoard() { var boardMock = new Mock <IStore <Board> >(); var listMock = new Mock <IStore <List> >(); var eventMock = new Mock <IStore <Event> >(); var userStoreMock = new Mock <IUserStore <ApplicationUser> >(); var userMock = new Mock <UserManager <ApplicationUser> >( userStoreMock.Object, null, null, null, null, null, null, null, null); var board = new Board { Id = 1, Title = "FGHJKL" }; ToDoController controller = new ToDoController(listMock.Object, userMock.Object, eventMock.Object, boardMock.Object); controller.PostBoard(board); boardMock.Verify(store => store.Add(board, 1)); }
public async Task CreateToDoListsReturnCreatedRoute() { //Arrange var mockService = new Mock <IToDoService>(); mockService.Setup( service => service.CreateToDoList(It.IsAny <int>(), It.IsAny <IEnumerable <CreateDTO> >()) ).ReturnsAsync(userId); var controller = new ToDoController(mockService.Object, _mockLogger, _mockCache); //Act var result = await controller.CreateList(userId, _mockCreateList); var resultResponse = result as CreatedAtRouteResult; //Assert Assert.IsInstanceOf <CreatedAtRouteResult>(resultResponse); Assert.AreEqual("Get", resultResponse.RouteName); }
public void RetreiveToDos_UnitTest() { _toDoRepository.Setup(d => d.Get(null, null, "")).Returns(_todos); var toDoController = new ToDoController(_mockContext.Object); var actionResult = toDoController.Get(); var okResult = actionResult as OkObjectResult; Assert.IsNotNull(okResult); Assert.AreEqual(200, okResult.StatusCode); var content = okResult.Value as IEnumerable <ToDo>; Assert.AreEqual(4, content.Count()); Assert.AreEqual("Sample Task", content.First().Name); }
public void Test_PutToDo_Id_Empty_Input() { Mock <ITodoRepository> mockRepository = new Mock <ITodoRepository>(); mockRepository.Setup(mr => mr.save(It.IsAny <ToDo>())).Returns(1); ToDoController tc = new ToDoController(mockRepository.Object); ToDo toDoITem = new ToDo { SlNo = 2, Item = "", Description = "" }; TodoResponse apiToDoResponse = tc.PutToDo(2, toDoITem); Assert.AreEqual(apiToDoResponse.responseHeader.error[0].errorCode, AppConstants.ITEM_EMPTY); Assert.AreEqual(apiToDoResponse.responseHeader.error[0].errorMessage, AppConstants.ITEM_EMPTY_MSG); Assert.AreEqual(apiToDoResponse.responseHeader.error[1].errorCode, AppConstants.DESCRIPTION_EMPTY); Assert.AreEqual(apiToDoResponse.responseHeader.error[1].errorMessage, AppConstants.DESCRIPTION_EMPTY_MSG); Assert.AreEqual(apiToDoResponse.responseHeader.statusMessage, AppConstants.Error); Assert.AreEqual(apiToDoResponse.responseHeader.statusCode, HttpStatusCode.BadRequest); }
public void TestCreateStatusWithErrorsOk() { //SETUP var status = new StatusGenericHandler(); var controller = new ToDoController(); var dto = new CreateTodoDto(); status.AddError("An error"); var actionResult = status.Response(controller, "Get", new { id = 7 }, dto); //ATTEMPT var statusCode = actionResult.GetStatusCode(); var rStatus = actionResult.CheckCreateResponse("Get", new { id = 7 }, dto); //VERIFY statusCode.ShouldEqual(CreateResponse.ErrorsStatusCode); rStatus.IsValid.ShouldBeTrue(rStatus.GetAllErrors()); rStatus.Message.ShouldEqual("Errors: An error"); }
public async Task DeleteFailure() { //Arrange var controller = new ToDoController(new ToDoBL(new ToDoRepository())); controller.Request = new HttpRequestMessage { Method = HttpMethod.Delete }; //Actual string id = "0"; var response = await controller.Delete(id); //Assert Assert.IsNotNull(response); Assert.IsNull(response.Content); Assert.IsFalse(response.IsSuccessStatusCode); Assert.AreEqual(HttpStatusCode.InternalServerError, response.StatusCode); }
public void TestUpdateAccurateId() { // Arrange ToDoController controller = new ToDoController(new ToDoBL(new ToDoRepository())); ToDoController controllerDelete = new ToDoController(new ToDoBL(new ToDoRepository())); // Act ViewResult resultGetAll = controllerDelete.Index().Result as ViewResult; ToDoList model = (ToDoList)resultGetAll.Model; //Please check the below id is correct otherwise this test case fail var updateLastRecord = model.Items[model.Items.Count - 1]; updateLastRecord.Name = "Updated via Unit Testing"; var result = (RedirectToRouteResult)controller.Update(updateLastRecord).Result; // Assert Assert.IsNotNull(result, "Not a redirect result"); Assert.IsFalse(result.Permanent); // Or IsTrue if you use RedirectToActionPermanent Assert.AreEqual("Index", result.RouteValues["Action"]); }
// Mock<ControllerContext> controllerContext; public ToDoControllerTest() { //controllerContext = new Mock<ControllerContext>(); _toDoServiceMock = new Mock <IToDoService>(); objController = new ToDoController(_toDoServiceMock.Object); appUser = new ApplicationUser(); listToDo = new List <ToDo> { new ToDo { Id = 1, Name = "US", CreatedDate = DateTime.Now, UpdatedDate = DateTime.Now, Start = DateTime.Now, End = DateTime.Now, OwnerBy = appUser }, new ToDo { Id = 2, Name = "India", CreatedDate = DateTime.Now, UpdatedDate = DateTime.Now, Start = DateTime.Now, End = DateTime.Now, OwnerBy = appUser }, new ToDo { Id = 3, Name = "Russia", CreatedDate = DateTime.Now, UpdatedDate = DateTime.Now, Start = DateTime.Now, End = DateTime.Now, OwnerBy = appUser } }; }
public void UpdateStateShouldUpdateStateOfExistingItemAndRedirectRouteToIndex() { var mockRepository = new Mock <IToDoItemsRepository>(); var item = new ToDoItem { ItemId = 1, Title = "Item1", DueDate = DateTime.Now }; mockRepository.Setup(repo => repo.UpdateItemState(It.IsAny <int>())).ReturnsAsync(item); var controller = new ToDoController(mockRepository.Object); var result = controller.UpdateState(item.ItemId).Result as RedirectToRouteResult; mockRepository.Verify(repo => repo.UpdateItemState(It.IsAny <int>()), Times.Once); Assert.AreEqual("Index", result.RouteValues.FirstOrDefault().Value); }
public void TestCreateWrongData() { // Arrange using (var repository = new ToDoRepository()) { using (var businessLogic = new ToDoBL(repository)) { using (ToDoController controller = new ToDoController(businessLogic)) { // Act ToDoItem item = new ToDoItem(); item.Name = ""; controller.ModelState.AddModelError("test", "test"); var result = controller.Create(item); //Assert Assert.IsTrue(result.Data.ToString() == "error", "Since the model is wrong so throwing error."); } } } }
public void DeleteFailure() { //Arrange var controller = new ToDoController(new ToDoBL(new ToDoRepository(), new DataCache())); controller.Request = new HttpRequestMessage { Method = HttpMethod.Delete, }; //Actual int id = 0; var response = controller.Delete(id); //Assert Assert.IsNotNull(response); Assert.IsNull(response.Content); Assert.IsFalse(response.IsSuccessStatusCode); Assert.AreEqual(HttpStatusCode.NotFound, response.StatusCode); }
public void AddItemShouldAddItemAndRedirectRouteToIndex() { var mockRepository = new Mock <IToDoItemsRepository>(); var addedItem = new ToDoItem { ItemId = 1, Title = "Item1", DueDate = DateTime.Now }; mockRepository.Setup(repo => repo.AddItem(It.IsAny <ToDoItem>())).ReturnsAsync(addedItem); var controller = new ToDoController(mockRepository.Object); var result = controller.AddItem(addedItem).Result as RedirectToRouteResult; mockRepository.Verify(repo => repo.AddItem(It.IsAny <ToDoItem>()), Times.Once); Assert.AreEqual("Index", result.RouteValues.FirstOrDefault().Value); }
public void UpdateBoardObjectChanged() { var board = new Board { Id = 1, Title = "FGHJKL" }; var boardMock = new Mock <IStore <Board> >(); boardMock.Setup(store => store.Update(board)); var listMock = new Mock <IStore <List> >(); var eventMock = new Mock <IStore <Event> >(); var userStoreMock = new Mock <IUserStore <ApplicationUser> >(); var userMock = new Mock <UserManager <ApplicationUser> >( userStoreMock.Object, null, null, null, null, null, null, null, null); ToDoController controller = new ToDoController(listMock.Object, userMock.Object, eventMock.Object, boardMock.Object); controller.PutBoard(board); boardMock.Verify(store => store.Update(board)); }
public void UpdateEventObjectChanged() { var eventObj = new Event { Id = 0, Title = "Test" }; var boardMock = new Mock <IStore <Board> >(); var listMock = new Mock <IStore <List> >(); var eventMock = new Mock <IStore <Event> >(); eventMock.Setup(store => store.Update(eventObj)); var userStoreMock = new Mock <IUserStore <ApplicationUser> >(); var userMock = new Mock <UserManager <ApplicationUser> >( userStoreMock.Object, null, null, null, null, null, null, null, null); ToDoController controller = new ToDoController(listMock.Object, userMock.Object, eventMock.Object, boardMock.Object); controller.PutEvent(eventObj); eventMock.Verify(store => store.Update(eventObj)); }
public void CheckCacheCount() { int CacheCount = 0; #region GetcacheCount //Arrange var controller = new CacheController(new ToDoBL(new ToDoRepository(), new DataCache())); //Actual var response = controller.GetItemCount(); int.TryParse(response.Data.ToString(), out CacheCount); #endregion #region Add item //Arrange var controllerAdd = new ToDoController(new ToDoBL(new ToDoRepository(), new DataCache())); int id = 100; ToDoItem request = new ToDoItem() { Id = id, Name = "Test Data" }; //Actual var responseAdd = controllerAdd.Create(request); #endregion #region Validate Count //Arrange var controllerValidate = new CacheController(new ToDoBL(new ToDoRepository(), new DataCache())); //Actual var responseValidate = controllerValidate.GetItemCount(); int CacheCountAfterInsert = 0; int.TryParse(responseValidate.Data.ToString(), out CacheCountAfterInsert); Assert.AreEqual((CacheCount + 1), CacheCountAfterInsert); #endregion }
public void TestCreateAccurateData() { // Arrange using (var repository = new ToDoRepository()) { using (var businessLogic = new ToDoBL(repository)) { using (ToDoController controller = new ToDoController(businessLogic)) { // Act ToDoItem item = new ToDoItem(); item.Name = "Test item"; var result = controller.Create(item); var data = result.Data.GetType().GetProperty("data"); var dataVal = (ToDoItem)data.GetValue(result.Data, null); //Assert Assert.IsTrue(dataVal.Id > 0, "Successfully created, ToDo Id retrived:" + dataVal.Id); } } } }