public HttpResponseMessage CreateCategory(CategoryModel model, string sessionKey) { var responseMessage = this.PerformOperationAndHandleExceptions(() => { var user = this.userRepository.GetAll() .Where(usr => usr.SessionKey == sessionKey).FirstOrDefault(); if (user == null) { throw new InvalidOperationException("User is not logged in or invalid session key."); } if (model == null) { throw new ArgumentNullException("The CategoryModel cannot be null."); } if (model.Name == null) { throw new ArgumentNullException("The category name cannot be null."); } Category category = new Category(); category.Name = model.Name; var threadTitles = model.threadTitles; var allThreadEntities = this.threadRepository.GetAll(); if (threadTitles != null) { foreach (var title in threadTitles) { var threadEntity = allThreadEntities.FirstOrDefault( entity => entity.Title == title); category.Threads.Add(threadEntity); } } this.categoryRepository.Add(category); var response = this.Request.CreateResponse(HttpStatusCode.Created, new { id = category.Id }); return response; }); return responseMessage; }
public void PostRequest_CreateCategoryTest_SuccessfulCreation() { FakeRepository<Category> categoryFakeRepository = new FakeRepository<Category>(); FakeRepository<User> userFakeRepository = new FakeRepository<User>(); FakeRepository<Thread> threadFakeRepository = new FakeRepository<Thread>(); string sessionKey = "01234567890123456789012345678901234567890123456789"; CategoryModel categoryModel = new CategoryModel() { Name = "Test category" }; User user = new User() { SessionKey = sessionKey }; userFakeRepository.Add(user); CategoriesController categoriesController = new CategoriesController( categoryFakeRepository, userFakeRepository, threadFakeRepository); SetupController(categoriesController); var response = categoriesController.CreateCategory(categoryModel, sessionKey); int expectedCategoryCount = 1; Assert.AreEqual(response.StatusCode, HttpStatusCode.Created); Assert.AreEqual(expectedCategoryCount, categoryFakeRepository.entities.Count); }