public void Arrange()
        {
            _fixture = new Fixture().Customize(new AutoMoqCustomization());

            _course = new Course("1-4-5", "test", 1);
            _cachedReservationResult = _fixture.Create <GetCachedReservationResult>();

            _mediator   = new Mock <IMediator>();
            _urlHelper  = new Mock <IExternalUrlHelper>();
            _controller = new ReservationsController(
                _mediator.Object,
                Mock.Of <ITrainingDateService>(),
                Mock.Of <IOptions <ReservationsWebConfiguration> >(),
                Mock.Of <ILogger <ReservationsController> >(),
                Mock.Of <IEncodingService>(),
                _urlHelper.Object);

            _mediator.Setup(mediator => mediator.Send(
                                It.IsAny <GetCachedReservationQuery>(),
                                It.IsAny <CancellationToken>()))
            .ReturnsAsync(() => _cachedReservationResult);

            _mediator.Setup(mediator => mediator.Send(
                                It.IsAny <CacheReservationCourseCommand>(),
                                It.IsAny <CancellationToken>()))
            .ReturnsAsync(Unit.Value);

            _mediator.Setup(mediator => mediator.Send(
                                It.IsAny <CacheReservationStartDateCommand>(),
                                It.IsAny <CancellationToken>()))
            .ReturnsAsync(Unit.Value);

            _mediator.Setup(m => m.Send(It.IsAny <GetCoursesQuery>(), It.IsAny <CancellationToken>()))
            .ReturnsAsync(new GetCoursesResult
            {
                Courses = new List <Course>
                {
                    _course
                }
            });
        }
Example #2
0
        public void Arrange()
        {
            _accountReservationsResult = new GetReservationResponse
            {
                Reservation = new Domain.Reservations.Reservation(null, _expectedReservationId, ExpectedAccountId, false, DateTime.UtcNow, DateTime.UtcNow, DateTime.UtcNow, ReservationStatus.Pending, null, 0, 0, "", 0, null)
            };

            _mediator = new Mock <IMediator>();
            _mediator.Setup(x => x.Send(It.Is <GetReservationQuery>(c => c.Id.Equals(_expectedReservationId)),
                                        It.IsAny <CancellationToken>()))
            .ReturnsAsync(_accountReservationsResult);
            _httpContext            = new Mock <HttpContext>();
            _reservationsController = new ReservationsController(Mock.Of <ILogger <ReservationsController> >(), _mediator.Object)
            {
                ControllerContext = { HttpContext      = _httpContext.Object,
                                      ActionDescriptor = new ControllerActionDescriptor
                                      {
                                          ControllerName = "reservations"
                                      } }
            };
        }
        public async Task EditPost_ValidInput_ReturnsViewResult()
        {
            // Arrange
            var reservation = new Reservation {
                ReservationId = 2, CustomerId = 2, MembershipId = 2, Details = "something new"
            };

            reservationRepoMock = new Mock <IReservationRepository>();
            reservationRepoMock
            .Setup(repo => repo.UpdateAsync(reservation))
            .Returns(Task.FromResult(1));
            var controller = new ReservationsController(reservationRepoMock.Object);

            // Act
            var result = await controller.Edit(2, reservation);

            // Assert
            var redirectToActionResult = result.Should().BeOfType <RedirectToActionResult>();

            redirectToActionResult.Subject.ActionName.Should().Be("Index");
        }
        public async Task Then_Redirects_To_The_Confirmation_Provider_View_When_Has_UkPrn(
            ReservationsRouteModel routeModel,
            PostReviewViewModel viewModel,
            CreateReservationResult createReservationResult,
            [Frozen] Mock <IMediator> mockMediator,
            ReservationsController controller)
        {
            mockMediator
            .Setup(mediator => mediator.Send(It.IsAny <CreateReservationCommand>(), CancellationToken.None))
            .ReturnsAsync(createReservationResult);

            var result = await controller.PostReview(routeModel, viewModel) as RedirectToRouteResult;

            result.Should().NotBeNull($"result was not a {typeof(RedirectToRouteResult)}");
            result.RouteName.Should().Be(RouteNames.ProviderCompleted);
            result.RouteValues.Should().ContainKey("id").WhichValue.Should().NotBe(Guid.Empty);
            result.RouteValues.Should().ContainKey("accountLegalEntityPublicHashedId")
            .WhichValue.Should().Be(createReservationResult.AccountLegalEntityPublicHashedId);
            result.RouteValues.Should().ContainKey("cohortReference")
            .WhichValue.Should().Be(createReservationResult.CohortRef);
        }
Example #5
0
        public void Post_With_Reservation_Calls_Repo_Add()
        {
            // Arrange
            var mockRepo = new Mock <IRepository <Reservation> >();

            mockRepo.Setup(mock => mock.Add(It.IsAny <Reservation>()));
            ReservationsController controller = new ReservationsController(mockRepo.Object);

            Reservation newReservation = new Reservation()
            {
                bookId    = 1,
                startDate = new System.DateTime(2016, 1, 1, 1, 0, 0),
                endDate   = new System.DateTime(2016, 1, 1, 2, 0, 0),
            };

            // Act
            controller.Post(newReservation);

            // Assert
            mockRepo.Verify(mock => mock.Add(It.Is <Reservation>(b => b == newReservation)), Times.Once);
        }
        public async Task ThenDoesNotSendsCommandIfNotMarkedAsReadAnd_Redirects_To_Route_In_Model(
            FundingRestrictionNotificationViewModel viewModel,
            ReservationsRouteModel routeModel,
            string expectedUserId,
            [Frozen] Mock <IMediator> mockMediator,
            ReservationsController controller)
        {
            //Arrange
            viewModel.MarkRuleAsRead = false;

            //act
            var actual = await controller.SaveRuleNotificationChoice(routeModel, viewModel) as RedirectToRouteResult;

            //assert
            mockMediator.Verify(m => m.Send(It.Is <MarkRuleAsReadCommand>(c =>
                                                                          c.Id.Equals(expectedUserId) &&
                                                                          c.RuleId.Equals(viewModel.RuleId) &&
                                                                          c.TypeOfRule.Equals(viewModel.TypeOfRule)), It.IsAny <CancellationToken>()), Times.Never);
            Assert.IsNotNull(actual);
            Assert.AreEqual(viewModel.RouteName, actual.RouteName);
        }
        public void PostValidDtoWhenSoldOut(int capacity, int quantity)
        {
            var repository = new FakeReservationsRepository();
            var now        = new DateTime(2019, 9, 27);
            var sut        = new ReservationsController(
                TimeSpan.FromHours(2.5),
                new[] { new Table(capacity) },
                repository,
                new ConstantClock(now));

            var dto = new ReservationDto
            {
                Date     = now.AddDays(2).ToString(),
                Quantity = quantity
            };
            var actual = sut.Post(dto);

            var c = Assert.IsAssignableFrom <ObjectResult>(actual);

            Assert.Equal(StatusCodes.Status500InternalServerError, c.StatusCode);
        }
Example #8
0
        public async Task And_No_UkPrn_Then_It_Uses_Employer_View_And_Uses_Provider_Id_If_Not_Null(
            ReservationsRouteModel routeModel,
            GetReservationResult mediatorResult,
            [Frozen] Mock <IMediator> mockMediator,
            [Frozen] Mock <IOptions <ReservationsWebConfiguration> > configuration,
            ReservationsController controller)
        {
            routeModel.UkPrn     = null;
            mediatorResult.UkPrn = null;
            mockMediator
            .Setup(mediator => mediator.Send(It.IsAny <GetReservationQuery>(), CancellationToken.None))
            .ReturnsAsync(mediatorResult);

            var result = await controller.Completed(routeModel);

            var viewResult = result.Should().BeOfType <ViewResult>().Subject;

            viewResult.ViewName.Should().Be(ViewNames.EmployerCompleted);
            var model = viewResult.Model.Should().BeOfType <CompletedViewModel>().Subject;

            model.UkPrn.Should().Be(routeModel.ProviderId);
        }
        public void PostValidDtoWhenNoPriorReservationsExist(
            int capacity,
            int quantity)
        {
            var repository = new FakeReservationsRepository();
            var now        = new DateTime(2019, 9, 24);
            var sut        = new ReservationsController(
                TimeSpan.FromHours(2.5),
                new[] { new Table(capacity) },
                repository,
                new ConstantClock(now));

            var dto = new ReservationDto
            {
                Date     = now.AddDays(1).ToString(),
                Quantity = quantity
            };
            var actual = sut.Post(dto);

            Assert.IsAssignableFrom <OkResult>(actual);
            Assert.NotEmpty(repository);
        }
Example #10
0
        public void Setup()
        {
            reservationsRepository = new MockReservationsRepository();
            reservationProcessor   = new ReservationProcessor(reservationsRepository);
            reservationController  = new ReservationsController(reservationsRepository,
                                                                reservationProcessor);

            reservationController.Request = new HttpRequestMessage
            {
                RequestUri = new Uri("http://localhost/api/reservation"),
            };
            reservationController.Configuration = new HttpConfiguration();
            reservationController.Configuration.Routes.MapHttpRoute(
                name: "DefaultApi",
                routeTemplate: "api/{controller}/{id}",
                defaults: new { id = RouteParameter.Optional });
            reservationController.RequestContext.RouteData = new HttpRouteData(
                route: new HttpRoute(),
                values: new HttpRouteValueDictionary {
                { "controller", "reservation" }
            });
        }
Example #11
0
        public static async Task Returns_reservations_data_for_each_active_date()
        {
            var activeDates = new[] { 15.February(2021), 16.February(2021), 18.February(2021) };

            var controller = new ReservationsController(
                CreateConfigurationRepository.WithDefaultConfiguration(),
                CreateDateCalculator.WithActiveDates(activeDates),
                CreateReservationRepository.WithReservations(activeDates, new List <Reservation>()),
                CreateUserRepository.WithUsers(DefaultUsers));

            var result = await controller.GetAsync();

            var resultValue = GetResultValue <ReservationsResponse>(result);

            Assert.NotNull(resultValue.Reservations);

            var visibleDays = GetVisibleDays(resultValue.Reservations);

            Assert.Equal(activeDates, visibleDays.Select(d => d.LocalDate));

            Assert.All(visibleDays, d => Assert.NotNull(d.Data));
        }
        public async Task Then_Redirects_To_The_Confirmation_Employer_View_When_No_UkPrn(
            ReservationsRouteModel routeModel,
            PostReviewViewModel viewModel,
            CreateReservationResult createReservationResult,
            [Frozen] Mock <IMediator> mockMediator,
            ReservationsController controller)
        {
            routeModel.UkPrn = null;
            var claim = new Claim(EmployerClaims.IdamsUserIdClaimTypeIdentifier, Guid.NewGuid().ToString());

            controller.HttpContext.User = new ClaimsPrincipal(new ClaimsIdentity(new[] { claim }));
            viewModel.Reserve           = true;
            mockMediator
            .Setup(mediator => mediator.Send(It.IsAny <CreateReservationCommand>(), CancellationToken.None))
            .ReturnsAsync(createReservationResult);

            var result = await controller.PostReview(routeModel, viewModel) as RedirectToRouteResult;

            result.Should().NotBeNull($"result was not a {typeof(RedirectToRouteResult)}");
            result.RouteName.Should().Be(RouteNames.EmployerCompleted);
            result.RouteValues.Should().ContainKey("id").WhichValue.Should().NotBe(Guid.Empty);
        }
        public async Task Then_It_Calls_Start_Date_Service_To_Get_Start_Dates(
            ReservationsRouteModel routeModel,
            GetCachedReservationResult cachedReservationResult,
            long accountLegalEntityId,
            [Frozen] Mock <IMediator> mockMediator,
            [Frozen] Mock <IEncodingService> mockEncodingService,
            [Frozen] Mock <ITrainingDateService> mockStartDateService,
            ReservationsController controller)
        {
            mockMediator
            .Setup(mediator => mediator.Send(It.IsAny <GetCachedReservationQuery>(), It.IsAny <CancellationToken>()))
            .ReturnsAsync(cachedReservationResult);
            mockEncodingService
            .Setup(service => service.Decode(
                       cachedReservationResult.AccountLegalEntityPublicHashedId,
                       EncodingType.PublicAccountLegalEntityId))
            .Returns(accountLegalEntityId);

            await controller.ApprenticeshipTraining(routeModel);

            mockStartDateService.Verify(provider => provider.GetTrainingDates(accountLegalEntityId), Times.Once);
        }
        private void OverlapDifferentRooms(Role ActorRole, Role OtherOwnerRole, bool IsMutable, bool Force)
        {
            var Actor            = new User(ActorRole, "a", true);
            var OtherOwner       = new User(OtherOwnerRole, "b", true);
            var server           = new Server();
            var room1            = new Room("room", "here", 1, true, false, 1);
            var room2            = new Room("room", "here", 1, true, false, 1);
            var startdate1       = new DateTime(2000, 1, 1);
            var enddate1         = new DateTime(2000, 1, 3);
            var otherreservation = new Reservation(startdate1, enddate1, true, IsMutable, "OtherReservation", room1);

            server.database.Users.Add(Actor);
            server.database.Users.Add(OtherOwner);
            server.database.Rooms.Add(room1);
            server.database.Rooms.Add(room2);

            server.database.Reservations.Add(otherreservation);
            server.database.Participants.Add(new Participant(otherreservation, OtherOwner, true, new DateTime(2000, 1, 1)));
            server.database.SaveChanges();

            var controller = new ReservationsController(server.database);

            controller.SetUserIdentity(Actor);

            var startdate2  = new DateTime(2000, 1, 2);
            var enddate2    = new DateTime(2000, 1, 4);
            var description = "Reservation";

            var result = controller.AddReservation(server.EmailService, startdate2, enddate2, description, room2.Id, Force);

            Assert.IsType <OkObjectResult>(result);
            var madereservation = server.database.Participants.Where(x => x.UserID == Actor.Id).First().Reservation;

            Assert.True(otherreservation.StartDate == startdate1 && otherreservation.EndDate == enddate1);
            Assert.True(otherreservation.Participants.First().User == OtherOwner);
            Assert.True(madereservation.StartDate == startdate2 && madereservation.EndDate == enddate2);
            Assert.True(madereservation.Participants.First().User == Actor);
        }
Example #15
0
        public void Put_With_Reservation_And_Id_Calls_Update()
        {
            // Arrange
            Reservation newReservation = new Reservation()
            {
                bookId    = 1,
                startDate = new System.DateTime(2016, 1, 1, 1, 0, 0),
                endDate   = new System.DateTime(2016, 1, 1, 2, 0, 0),
            };
            var mockRepo = new Mock <IRepository <Reservation> >();

            mockRepo.Setup(mock => mock.Update(It.IsAny <Reservation>(), It.IsAny <int>()));
            ReservationsController controller = new ReservationsController(mockRepo.Object);

            // Act
            controller.Put(newReservation, 1);

            // Assert
            mockRepo.Verify(mock => mock.Update(
                                It.Is <Reservation>(b => b == newReservation),
                                It.Is <int>(x => x == 1)),
                            Times.Once);
        }
        public ReservationsControllerShould()
        {
            _reservationsQueryMock = new Mock <IReservationsQuery>();
            _mockHttpContext       = new Mock <HttpContext>();
            _loggerMock            = new Mock <ILogger>();

            _user = new ClaimsPrincipal(new ClaimsIdentity(new Claim[]
            {
                new Claim(ClaimTypes.NameIdentifier, "1")
            }));

            _sut = new ReservationsController(
                _reservationsQueryMock.Object,
                _loggerMock.Object);

            _sut.ControllerContext = new ControllerContext()
            {
                HttpContext = new DefaultHttpContext()
                {
                    User = _user
                }
            };
        }
Example #17
0
        public async Task And_ArgumentException_Then_Returns_BadRequest(
            Guid reservationId,
            bool employerDeleted,
            ArgumentException argumentException,
            [Frozen] Mock <IMediator> mockMediator,
            ReservationsController controller)
        {
            mockMediator
            .Setup(mediator => mediator.Send(
                       It.IsAny <DeleteReservationCommand>(),
                       It.IsAny <CancellationToken>()))
            .ThrowsAsync(argumentException);

            var result = await controller.Delete(reservationId, employerDeleted) as BadRequestObjectResult;

            result.Should().NotBeNull();
            result.StatusCode.Should().Be(400);
            var error = result.Value as ArgumentErrorViewModel;

            error.Should().NotBeNull();
            error.Message.Should().Be(argumentException.Message);
            error.Params.Should().Be(argumentException.ParamName);
        }
Example #18
0
        public void GetAsync_Return_Empty_Reservation_List()
        {
            //Arrange

            int expectedStatusCode = 200;

            IEnumerable <ReservationDomainModel>         reservationsIEn = null;
            Task <IEnumerable <ReservationDomainModel> > responseTask    = Task.FromResult(reservationsIEn);

            _reservationService = new Mock <IReservationService>();
            _reservationService.Setup(x => x.GetAllAsync()).Returns(responseTask);
            ReservationsController reservationsController = new ReservationsController(_reservationService.Object);

            //Act
            var result     = reservationsController.GetAsync().ConfigureAwait(false).GetAwaiter().GetResult().Result;
            var resultList = ((OkObjectResult)result).Value;
            List <ReservationDomainModel> reservationDomainModelsResult = (List <ReservationDomainModel>)resultList;

            //Assert
            Assert.IsNotNull(reservationDomainModelsResult);
            Assert.IsInstanceOfType(result, typeof(OkObjectResult));
            Assert.AreEqual(expectedStatusCode, ((OkObjectResult)result).StatusCode);
        }
Example #19
0
        public void PostReturnsCorrectResultWhenCapacityIsInsufficient()
        {
            var repo = new Mock <IReservationsRepository>();
            var sut  = new ReservationsController(repo.Object);

            repo
            .Setup(r => r.ReadReservedSeats(It.IsAny <DateTime>()))
            .Returns(sut.Capacity);

            var actual =
                sut.Post(
                    new ReservationDto
            {
                Date     = "2016-05-31",
                Name     = "Mark Seemann",
                Email    = "*****@*****.**",
                Quantity = 1
            });

            var statusCode = Assert.IsAssignableFrom <StatusCodeResult>(actual);

            Assert.Equal(HttpStatusCode.Forbidden, statusCode.StatusCode);
        }
        public async Task Then_It_Returns_The_ViewModel(
            ReservationsRouteModel routeModel,
            GetCachedReservationResult cachedReservationResult,
            [Frozen] Mock <IMediator> mockMediator,
            ReservationsController controller)
        {
            mockMediator
            .Setup(mediator => mediator.Send(It.IsAny <GetCachedReservationQuery>(), It.IsAny <CancellationToken>()))
            .ReturnsAsync(cachedReservationResult);
            routeModel.FromReview = false;

            var result = await controller.Review(routeModel);

            var viewModel = result.Should().BeOfType <ViewResult>()
                            .Which.Model.Should().BeOfType <ReviewViewModel>().Subject;

            viewModel.RouteModel.Should().BeEquivalentTo(routeModel);
            viewModel.TrainingDate.Should().Be(cachedReservationResult.TrainingDate);
            viewModel.CourseDescription.Should().Be(cachedReservationResult.CourseDescription);
            viewModel.AccountLegalEntityName.Should().Be(cachedReservationResult.AccountLegalEntityName);
            viewModel.AccountLegalEntityPublicHashedId.Should().Be(cachedReservationResult.AccountLegalEntityPublicHashedId);
            viewModel.RouteModel.FromReview.Should().BeTrue();
        }
        public async Task And_CachedReservationNotFoundException_And_No_Ukprn_Then_Redirects_To_EmployerIndex(
            ReservationsRouteModel routeModel,
            PostReviewViewModel viewModel,
            CachedReservationNotFoundException notFoundException,
            [Frozen] Mock <IMediator> mockMediator,
            ReservationsController controller)
        {
            routeModel.UkPrn = null;
            var claim = new Claim(EmployerClaims.IdamsUserIdClaimTypeIdentifier, Guid.NewGuid().ToString());

            controller.HttpContext.User = new ClaimsPrincipal(new ClaimsIdentity(new[] { claim }));
            viewModel.Reserve           = true;
            mockMediator.Setup(x => x.Send(It.IsAny <CreateReservationCommand>(), It.IsAny <CancellationToken>()))
            .ThrowsAsync(notFoundException);

            var actual = await controller.PostReview(routeModel, viewModel);

            actual.Should().NotBeNull();
            var redirectToRouteResult = actual as RedirectToRouteResult;

            redirectToRouteResult.Should().NotBeNull();
            redirectToRouteResult?.RouteName.Should().Be(RouteNames.EmployerIndex);
        }
Example #22
0
        public void PostReturnsCorrectResultAndHasCorrectStateOnAcceptableRequest()
        {
            var json =
                new ReservationDto
            {
                Date     = "2016-05-31",
                Name     = "Mark Seemann",
                Email    = "*****@*****.**",
                Quantity = 1
            };
            var repo = new Mock <IReservationsRepository>();

            repo
            .Setup(r => r.ReadReservedSeats(new DateTime(2016, 5, 31)))
            .Returns(0);
            var sut = new ReservationsController(repo.Object);

            var actual = sut.Post(json);

            Assert.IsAssignableFrom <OkResult>(actual);
            repo.Verify(
                r => r.SaveReservation(new DateTime(2016, 5, 31), json));
        }
        public void PostValidDtoWhenSoldOut()
        {
            //Arrange
            var dto = new ReservationDto {
                Date = "01/01/1970"
            };

            Mock <IValidator> validator = GetValidator(dto);
            Mock <IMapper>    mapper    = GetMapper(dto);

            var md = new Mock <IMaƮtreD>();

            md.Setup(m => m.TryAccept(It.IsAny <Reservation>())).Returns((int?)null);
            ReservationsController sut = new ReservationsController(validator.Object, mapper.Object, md.Object);

            //Act
            var actual = sut.Post(dto);

            //Assert
            var c        = Assert.IsAssignableFrom <ObjectResult>(actual);
            var expected = 500;

            Assert.Equal(expected, c.StatusCode);
        }
Example #24
0
        public void ReservationsController_Post_InvalidModelState()
        {
            //Arrange
            string expectedMessage    = "Invalid Model State";
            int    expectedStatusCode = 400;

            ReservationsController reservationsController = new ReservationsController(_mockReservationService.Object, _mockUserService.Object, _mockProjectionService.Object);

            reservationsController.ModelState.AddModelError("key", "Invalid Model State");

            //Act
            var result             = reservationsController.PostAsync(_createReservationModel).ConfigureAwait(false).GetAwaiter().GetResult().Result;
            var resultMessage      = (BadRequestObjectResult)result;
            var resultMassageValue = ((BadRequestObjectResult)result).Value;
            var errorResult        = ((SerializableError)resultMassageValue).GetValueOrDefault("key");
            var message            = (string[])errorResult;


            //Assert
            Assert.IsNotNull(resultMessage);
            Assert.AreEqual(expectedMessage, message[0]);
            Assert.IsInstanceOfType(result, typeof(BadRequestObjectResult));
            Assert.AreEqual(expectedStatusCode, resultMessage.StatusCode);
        }
Example #25
0
        public void Arrange()
        {
            _mediator = new Mock <IMediator>();
            _accountReservationsResult = new FindAccountReservationsResult {
                Reservations = new List <Domain.Reservations.Reservation>
                {
                    new Domain.Reservations.Reservation(Guid.NewGuid(), ExpectedProviderId, DateTime.Now, 3, "Test Name")
                },
                NumberOfRecordsFound = 3,
                Filters = new SearchFilters
                {
                    CourseFilters    = new [] { "Baker - Level 1", "Banking - Level 2" },
                    EmployerFilters  = new [] { "Test Ltd", "Acme Bank" },
                    StartDateFilters = new [] { DateTime.Now.AddDays(-1).ToString("d"), DateTime.Now.ToString("d") }
                }
            };

            _mediator.Setup(x => x.Send(It.Is <FindAccountReservationsQuery>(c =>
                                                                             c.ProviderId.Equals(ExpectedProviderId)),
                                        It.IsAny <CancellationToken>()))
            .ReturnsAsync(_accountReservationsResult);

            _reservationsController = new ReservationsController(Mock.Of <ILogger <ReservationsController> >(), _mediator.Object);
        }
        public async Task Then_It_Sets_The_Back_Link_Correctly_Coming_From_The_Review_Screen(
            ReservationsRouteModel routeModel,
            GetCoursesResult getCoursesResult,
            GetCachedReservationResult cachedReservationResult,
            [Frozen] Mock <IMediator> mockMediator,
            ReservationsController controller)
        {
            cachedReservationResult.CohortRef = string.Empty;
            mockMediator
            .Setup(mediator => mediator.Send(It.IsAny <GetCachedReservationQuery>(), It.IsAny <CancellationToken>()))
            .ReturnsAsync(cachedReservationResult);
            mockMediator
            .Setup(mediator => mediator.Send(It.IsAny <GetCoursesQuery>(), It.IsAny <CancellationToken>()))
            .ReturnsAsync(getCoursesResult);
            routeModel.FromReview = true;

            var result = await controller.ApprenticeshipTraining(routeModel);

            var viewModel = result.Should().BeOfType <ViewResult>()
                            .Which.Model.Should().BeOfType <ApprenticeshipTrainingViewModel>()
                            .Subject;

            viewModel.BackLink.Should().Be(RouteNames.ProviderReview);
        }
        private Tuple <Server, IActionResult> AddReservationOverlap(User Actor, User OtherOwner, bool IsMutable, bool Force)
        {
            var server           = new Server();
            var room             = new Room("room", "here", 1, true, false, 1);
            var otherreservation = new Reservation(new DateTime(2000, 1, 1), new DateTime(2000, 1, 3), true, IsMutable, "OtherReservation", room);

            server.database.Users.Add(Actor);
            server.database.Users.Add(OtherOwner);
            server.database.Rooms.Add(room);

            server.database.Reservations.Add(otherreservation);
            server.database.Participants.Add(new Participant(otherreservation, OtherOwner, true, new DateTime(2000, 1, 1)));
            server.database.SaveChanges();

            var controller = new ReservationsController(server.database);

            controller.SetUserIdentity(Actor);

            var startdate   = new DateTime(2000, 1, 2);
            var enddate     = new DateTime(2000, 1, 4);
            var description = "Reservation";

            return(new Tuple <Server, IActionResult>(server, controller.AddReservation(server.EmailService, startdate, enddate, description, room.Id, Force)));
        }
        public void PostPastReservationWhenNoPriorReservationsExist(
            int capacity,
            int quantity)
        {
            var repository = new FakeReservationsRepository();
            var now        = new DateTime(2019, 8, 21);
            var sut        = new ReservationsController(
                TimeSpan.FromHours(2.5),
                new[] { new Table(capacity) },
                repository,
                new ConstantClock(now));

            var dto = new ReservationDto
            {
                Date     = now.Subtract(TimeSpan.FromDays(1)).ToString(),
                Quantity = quantity
            };
            var actual = sut.Post(dto);

            var br  = Assert.IsAssignableFrom <BadRequestObjectResult>(actual);
            var msg = Assert.IsAssignableFrom <string>(br.Value);

            Assert.NotEmpty(msg);
        }
        public async Task EditPost_InvalidModelState_ReturnsNotFoundResult()
        {
            // Arrange
            var reservation = new Reservation {
                ReservationId = 2
            };

            reservationRepoMock = new Mock <IReservationRepository>();
            reservationRepoMock
            .Setup(repo => repo.UpdateAsync(reservation))
            .Returns(Task.FromResult(1));
            var controller = new ReservationsController(reservationRepoMock.Object);

            controller.ModelState.AddModelError("Details", "Length too large");

            // Act
            var result = await controller.Edit(2, reservation);

            // Assert
            var viewResult = result.Should().BeOfType <ViewResult>();
            var model      = (Reservation)viewResult.Subject.Model;

            model.Should().Be(reservation);
        }
Example #30
0
        public void GetById_Return_NotFound()
        {
            //Arrange
            ReservationDomainModel reservationDomainModel = null;
            string expectedMessage = Messages.RESERVATION_NOT_FOUND;

            int expectedStatusCode = 404;
            Task <ReservationDomainModel> responseTask = Task.FromResult(reservationDomainModel);

            _reservationService = new Mock <IReservationService>();
            _reservationService.Setup(x => x.GetByIdAsync(It.IsAny <Guid>())).Returns(responseTask);
            ReservationsController reservationsController = new ReservationsController(_reservationService.Object);

            //Act
            var    result       = reservationsController.GetById(Guid.NewGuid()).ConfigureAwait(false).GetAwaiter().GetResult().Result;
            var    objectResult = ((NotFoundObjectResult)result).Value;
            string errorMessage = (string)objectResult;

            //Assert
            Assert.IsNotNull(objectResult);
            Assert.IsInstanceOfType(result, typeof(NotFoundObjectResult));
            Assert.AreEqual(expectedStatusCode, ((NotFoundObjectResult)result).StatusCode);
            Assert.AreEqual(expectedMessage, errorMessage);
        }