Exemplo n.º 1
0
 private MainViewModel CreateMainViewModel(IFixture fixture, IMessenger messenger = null)
 {
     var channel = fixture.Create<IChannel<SaveCmdApplicationConfigurationCommand>>();
     fixture.Register<ICmdApplicationConfigurationViewModelFactory>(() => fixture.Create<CmdApplicationConfigurationViewModelFactory>());
     fixture.Inject(messenger ?? new Messenger());
     return fixture.Build<MainViewModel>().OmitAutoProperties().Create();
 }
Exemplo n.º 2
0
			public static void ShouldUpdateTags( [Frozen] SpPortalLicenseApi portalApi, RandomLicenseFromListFixture license, ExistingTagsFixture tags, IFixture fixture )
			{
				var valuesForEachDefinedTag = tags.Tags
					.Select( ct => fixture.Build<SpPortalLicenseApi.LicenseTag>().With( x => x.Id, ct.Id ).CreateAnonymous() )
					.ToList();

				var licenseTagsAssignmentHref = license.Selected._embedded.CustomerTags._links.self.href;
				var apiResult = portalApi.PutLicenseTags( licenseTagsAssignmentHref, valuesForEachDefinedTag );
				Assert.Equal( ResponseStatus.Completed, apiResult.ResponseStatus );
				Assert.Equal( HttpStatusCode.Accepted, apiResult.StatusCode );

				Verify.EventuallyWithBackOff( () =>
				{
					//Retrieve the license again (if it was supported, just GETting the tags subresource would be sufficient to prove the point)
					var updatedLicense = portalApi.GetLicense( license.Selected._links.self.href );

					//Verify that all the tags on the license match
					Assert.Equal( ResponseStatus.Completed, updatedLicense.ResponseStatus );
					Assert.NotNull( updatedLicense.Data._embedded.CustomerTags.results );
					Assert.NotEmpty( updatedLicense.Data._embedded.CustomerTags.results );
					// TOOD use xUnit 1.9 and/or Ploeh.semanticComparison to make this cleaner
					Assert.Equal(
						updatedLicense.Data._embedded.CustomerTags.results.OrderBy( x => x.Id ).Select( x => Tuple.Create( x.Id, x.Value ) ).ToArray(),
						valuesForEachDefinedTag.OrderBy( x => x.Id ).Select( x => Tuple.Create( x.Id, x.Value ) ).ToArray() );
				} );
			}
Exemplo n.º 3
0
 public void Setup()
 {
     _fixture = new Fixture().Customize(new AutoMoqCustomization());
     var container = _fixture.Freeze<Mock<IContainer>>();
     _sut =
         _fixture.Build<AutoMappingMapper>().FromFactory(
             () => new AutoMappingMapper(Mapper.Engine, container.Object)).CreateAnonymous();
 }
 private static CmdApplicationConfiguration GetApplicationConfiguration(string applicationName, string friendlyName, IFixture fixture)
 {
     // TODO: This can be generalized 
     return fixture.Build<CmdApplicationConfiguration>()
         .FromSeed(a => new CmdApplicationConfiguration(
             (Name)friendlyName,
             (Name)applicationName,
             new System.Collections.ObjectModel.ReadOnlyCollection<IParameter>(new List<IParameter>())))
             .Create();
 }
Exemplo n.º 5
0
            public void Customize(IFixture fixture)
            {
                //we freeze the HttpRequestContext so that the same context is injected into the controller and the request object
                //otherwise, a conflict would happen and an InvalidOperationException would be thrown
                var requestContext = fixture.Build<HttpRequestContext>()
                    .Without(x => x.ClientCertificate)
                    .Create();

                fixture.Inject(requestContext);
            }
Exemplo n.º 6
0
        public static int CreateRandomBetween(this IFixture fixture, int from, int to)
        {
            if (from == to)
            {
                return((int)from);
            }

            return(fixture.Build <int>()
                   .FromFactory(new RandomNumericSequenceGenerator(from, to))
                   .Create());
        }
        private Guid GetCancelledBookingId()
        {
            var order = _fixture.Build <Order>()
                        .With(o => o.Status, 1)
                        .Create();

            _context.Add(order);
            _context.SaveChanges();

            return(order.Id);
        }
Exemplo n.º 8
0
        public async Task GetTemperatureTestAsync(Temperature unit, double input, double expected)
        {
            fixture.Customize(new TemperatureGuageCustomization(unit, input))
            .Customize(new TemperatureOptionsCustomization(unit));

            SystemController mockController = fixture.Build <SystemController>()
                                              .OmitAutoProperties()
                                              .Create();

            var result = await mockController.SystemTemperatureAsync();

            Assert.IsType <OkObjectResult>(result);
            OkObjectResult okResult = (OkObjectResult)result;

            Assert.IsType <TemperatureResult>(okResult.Value);
            TemperatureResult tempResult = (TemperatureResult)okResult.Value;

            Assert.Equal(expected, tempResult.Temperature);
            Assert.Equal(unit.ToString(), tempResult.Unit);
        }
        public void ValidateRequest_DoctorWithEmailAddressAlreadyExists_ReturnsFailedValidationResult()
        {
            //arrange
            var request = GetValidRequest();

            var existingDoctor = _fixture
                                 .Build <Doctor>()
                                 .With(x => x.Email, request.Email)
                                 .Create();

            _context.Add(existingDoctor);
            _context.SaveChanges();

            //act
            var res = _addDoctorRequestValidator.ValidateRequest(request);

            //assert
            res.PassedValidation.Should().BeFalse();
            res.Errors.Should().Contain(ValidationErrorMessages.EntityWithEmailAlreadyExists(nameof(Doctor)));
        }
Exemplo n.º 10
0
        private AddBookingRequest GetValidRequest()
        {
            var request = _fixture.Build <AddBookingRequest>()
                          .With(x => x.DoctorId, 1)
                          .With(x => x.PatientId, 1)
                          .With(x => x.StartTime, _clockMock.Object.UtcNow.AddHours(1).UtcDateTime)
                          .With(x => x.EndTime, _clockMock.Object.UtcNow.AddHours(2).UtcDateTime)
                          .Create();

            return(request);
        }
        public void AndEmployerDescriptionExistsInTheRequest()
        {
            var mapper  = _fixture.Create <CreateApprenticeshipParametersMapper>();
            var request = _fixture
                          .Build <CreateApprenticeshipRequest>()
                          .Create();
            var empInfo = _fixture
                          .Build <EmployerInformation>()
                          .Create();
            var parameters = mapper.MapFromRequest(request, empInfo);

            parameters.EmployerDescription.Should().Be(request.EmployerDescription);
        }
Exemplo n.º 12
0
 private CmdApplicationMeta GetApplicationConfigurationMeta(string applicationName, string friendlyName, IFixture fixture)
 {
     // TODO: This can be generalized 
     fixture.Inject<Type>(typeof(IParameter));
     return fixture.Build<CmdApplicationMeta>()
         .FromSeed(a => new CmdApplicationMeta(
             (Name)friendlyName,
             (Name)applicationName,
             new List<ParameterMeta>()))
             .Create();
 }
Exemplo n.º 13
0
        public void ValidateRequest_AllChecksPass_ReturnsPassedValidationResult()
        {
            var patient = _fixture.Create <Patient>();
            var doctor  = _fixture.Create <Doctor>();

            _context.Patient.Add(patient);
            _context.Doctor.Add(doctor);

            _context.SaveChanges();

            var request = _fixture.Build <AddAppointmentRequest>()
                          .With(x => x.PatientId, patient.Id)
                          .With(x => x.DoctorId, doctor.Id)
                          .With(x => x.StartTime, DateTime.UtcNow.AddYears(1))
                          .Create();

            var res = _sut.ValidateRequest(request);

            res.PassedValidation.Should().BeTrue();
        }
Exemplo n.º 14
0
        public void ValidateRequest_PatientWithEmailAddressAlreadyExists_ReturnsFailedValidationResult()
        {
            //arrange
            var request = GetValidRequest();

            var existingPatient = _fixture
                                  .Build <Patient>()
                                  .With(x => x.Email, request.Email)
                                  .Create();

            _context.Add(existingPatient);
            _context.SaveChanges();

            //act
            var res = _addPatientRequestValidator.ValidateRequest(request);

            //assert
            res.PassedValidation.Should().BeFalse();
            res.Errors.Should().Contain("A patient with that email address already exists");
        }
        public void Update_ExistingAdultCustomer_Success_Composed(
            [AsAdultPersisted] Customer e,
            CustomerManager sut,
            IFixture fixture)
        {
            var data = fixture.Build <CustomerUpdate>()
                       .With(x => x.ID, e.ID)
                       .Create();

            sut.Update(data);
        }
Exemplo n.º 16
0
        public static IPostprocessComposer <OutputGroupModel> WithItems(
            this IPostprocessComposer <OutputGroupModel> composer, IDictionary <string, int> itemsDefinitions,
            IFixture fixture)
        {
            var items = itemsDefinitions?.Select(def => fixture.Build <OutputItemModel>()
                                                 .WithId(def.Key)
                                                 .WithCount(def.Value)
                                                 .Create());

            return(items != null?composer.With(m => m.Items, items) : composer);
        }
        public async Task ExecuteRethrowsIPassThroughExceptionAndDoesNotLog()
        {
            //Arrange
            var coreActionHandler = new ConnectedServiceActionHandler(_serviceName);
            var log = new Mock <ILogger>();

            async Task func()
            {
                await Task.Yield();

                throw _fixture.Build <RecordNotFoundException>().Create();
            }

            //Act
            var exception = await Assert.ThrowsAsync <RecordNotFoundException>(async() => await coreActionHandler.Execute(log.Object, func));

            //Assert
            Assert.NotNull(exception);
            log.Verify(a => a.Error(It.IsAny <Exception>(), It.IsAny <string>()), Times.Never);
        }
Exemplo n.º 18
0
        public async Task GetAsyncById_ShouldReturnUserDto(int id)
        {
            // Arrange
            var user = _fixture.Build <User>()
                       .With(u => u.Id, id)
                       .Create();

            _userRepository.GetAsync(id).Returns(user);

            // Act
            var dto = await _sut.GetAsync(user.Id);

            // Assert
            dto.ShouldNotBeNull();
            dto.Id.ShouldBe(user.Id);
            dto.UserName.ShouldBe(user.UserName);
            dto.Email.ShouldBe(user.Email);
            dto.Role.ShouldBe(user.UserRoles.Select(ur => ur.Role.Name.ToString()).FirstOrDefault());
            await _userRepository.Received(1).GetAsync(Arg.Is(id));
        }
Exemplo n.º 19
0
 public static Field GenerateField(IFixture fixture, FieldExactTypes type)
 {
     return(fixture.Build <Field>()
            .OmitAutoProperties()
            .Do(c => c.Init())
            .With(f => f.Id)
            .With(f => f.Name)
            .With(f => f.IsClassifier, false)
            .With(f => f.ExactType, type)
            .Create());
 }
Exemplo n.º 20
0
        public async Task Post_ShouldReturnCorrectResult(IFixture fixture, FileController sut)
        {
            // arrange
            var files = fixture.Build <IFormFileCollection>().Create();

            // act
            var actual = await sut.Post(files);

            // assert
            actual.ShouldBeOfType <FileStreamResult>();
        }
        public CsvDbUpdateClassifierArticleTests()
        {
            _fixture = new Fixture().Customize(new AutoMoqCustomization()
            {
                ConfigureMembers = true
            });
            _postProcessFieldComposer = _fixture.Build <Field>().FromFactory(CsvDbUpdateTestHelpers.GenerateField(_fixture)).OmitAutoProperties();
            _fixture.Customize <Field>(composer => _postProcessFieldComposer);

            QPContext.CurrentDbConnectionString = _fixture.Create <string>();
        }
        public BookUpdateCommandHandlerTests()
        {
            _fixture = new Fixture();
            _fixture.Behaviors.Add(new OmitOnRecursionBehavior());

            _context = InitializeDatabase();

            _testCommand = CreateTestCommand(
                Guid.NewGuid(),
                CompletionStatusReference.Completed,
                false,
                false,
                1,
                Guid.NewGuid());

            var checkout = _fixture
                           .Build <CheckoutRecord>()
                           .With(c => c.ModifiedOn, DateTimeOffset.UtcNow)
                           .Create();

            var itemStorage = _fixture
                              .Build <ItemStorageRecord>()
                              .With(a => a.ModifiedOn, DateTimeOffset.UtcNow)
                              .Create();

            _testBook = _fixture
                        .Build <BookRecord>()
                        .With(a => a.Id, _testCommand.BookId)
                        .With(a => a.Author, _testCommand.Author)
                        .With(a => a.Checkout, checkout)
                        .With(a => a.UpdatedOn, DateTimeOffset.UtcNow)
                        .With(a => a.ItemStorage, itemStorage)
                        .With(a => a.Type, _testCommand.Type)
                        .With(a => a.TimesCompleted, 1)
                        .With(a => a.Title, _testCommand.Title)
                        .With(a => a.User, _testCommand.User)
                        .With(a => a.UserId, _testCommand.User.Id)
                        .Create();

            _handler = new BookUpdateCommandHandler(_context);
        }
        public async Task PublishAllPendingEvents_sends_app_pending_events()
        {
            // Arrange
            IEnumerable <FakeUserCreated> createdEvents = fixture
                                                          .Build <FakeUserCreated>()
                                                          .With(e => e.Version, 1)
                                                          .CreateMany();
            var eventStore = new SqlEventStore(() => new DataContext(), serializer);

            foreach (FakeUserCreated createdEvent in createdEvents)
            {
                await eventStore.SaveEvents <FakeUser>(new[] { createdEvent });
            }

            var sentEvents = new List <Envelope>();

            Mock.Get(messageBus)
            .Setup(
                x =>
                x.SendBatch(
                    It.IsAny <IEnumerable <Envelope> >(),
                    It.IsAny <CancellationToken>()))
            .Callback <IEnumerable <Envelope>, CancellationToken>((batch, t) => sentEvents.AddRange(batch))
            .Returns(Task.FromResult(true));

            // Act
            await sut.PublishAllPendingEvents(CancellationToken.None);

            // Assert
            foreach (FakeUserCreated createdEvent in createdEvents)
            {
                sentEvents
                .Select(e => e.Message)
                .OfType <FakeUserCreated>()
                .Where(e => e.SourceId == createdEvent.SourceId)
                .Should()
                .ContainSingle()
                .Which
                .ShouldBeEquivalentTo(createdEvent);
            }
        }
        public async Task Handler_Returns_Unauthorized_If_Token_Is_Expired()
        {
            var token = _fixture
                        .Build <RefreshTokenRecord>()
                        .With(t => t.ExpiresOn, DateTimeOffset.UtcNow.AddDays(-1))
                        .With(t => t.Token, _testRequest.RefreshToken)
                        .Create();

            var user = _fixture
                       .Build <ApplicationUser>()
                       .With(u => u.RefreshTokens, new[] { token })
                       .Create();

            _queryDispatcher
            .Setup(x => x.Dispatch <UserGetByRefreshTokenQuery, Result <ApplicationUser> >(It.Is <UserGetByRefreshTokenQuery>(q => q != null)))
            .ReturnsAsync(Result.Success(user));

            var result = await _handler.Handle(_testRequest, CancellationToken.None);

            result.Should().BeOfType <UnauthorizedResult>();
        }
        public async Task Download_NotExistingFile_ReturnedNotFoundResposne()
        {
            //Arrange
            var fileName = _fixture.Create <string>();

            var expectedDownloadInformation = _fixture
                                              .Build <DownloadInformationDto>()
                                              .With(dto => dto.Status, HttpStatusCode.NotFound.ToString("G"))
                                              .Without(dto => dto.Content)
                                              .Create();

            _documentHandlerMock
            .Setup(handler => handler.DownloadAsync(fileName))
            .ReturnsAsync(expectedDownloadInformation);

            //Act
            var actionResult = await _sut.Download(fileName);

            //Assert
            actionResult.ShouldBeOfType <NotFoundObjectResult>();
        }
        public void ExplicitMockOrInstanceUsage()
        {
            var mockLogger = new Mock <IFileLogger>();

            _fixture.Register(() => mockLogger.Object);          // add the mock to this fixture

            var orderService = _fixture.Create <OrderService>(); // will use the mockLogger to create

            var order = _fixture.Build <Order>()
                        .With(o => o.Id, 0)
                        .With(o => o.Customer, _fixture.Build <Customer>()
                              .With(c => c.CreditRating, 300)
                              .Without(c => c.OrderHistory).Create)           // AutoFixture doesn't support loops in object hierarchies
                        .Create();

            // Act
            orderService.PlaceOrder(order);

            // Assert
            mockLogger.Verify(l => l.Log(It.IsAny <string>()), "OrderService created.");
        }
Exemplo n.º 27
0
        public void AddBooking_ValidatesRequest()
        {
            //arrange
            var existingPatient = _fixture
                                  .Build <Patient>()
                                  .With(x => x.ClinicId, 1)
                                  .Create();

            _context.Patient.Add(existingPatient);
            _context.SaveChanges();

            var request = _fixture.Create <NewBookingRequest>();

            request.PatientId = existingPatient.Id;

            //act
            _bookingService.AddBooking(request);

            //assert
            _validator.Verify(x => x.ValidateRequest(request), Times.Once);
        }
        public async Task DownloadAsync_ReturnsDownloadInformation()
        {
            //Arrange
            await using var fileContentStream = new MemoryStream();
            var expectedDownloadInformation = _fixture.Build <FileDownloadInfo>()
                                              .With(info => info.Content, fileContentStream)
                                              .Create();
            var fileName = _fixture.Create <string>();

            _fileStorageHandlerMock
            .Setup(handler => handler.DownloadFileAsync(fileName))
            .ReturnsAsync(expectedDownloadInformation);

            //Act
            var actualDownloadInformation = await _sut.DownloadAsync(fileName);

            //Assert
            actualDownloadInformation.Status.ShouldBe(expectedDownloadInformation.Status);
            actualDownloadInformation.Content.ShouldBe(expectedDownloadInformation.Content);
            actualDownloadInformation.ContentType.ShouldBe(expectedDownloadInformation.ContentType);
        }
        public async Task ScreeningAdded_event_handler_add_screening_entity_correctly(
            MovieCreated movieCreated,
            Theater theater,
            InMemoryMovieRepository movieRepositoryDouble,
            InMemoryTheaterRepository theaterReaderStub,
            IFixture builder)
        {
            // Arrange
            theaterReaderStub.Data[theater.Id] = theater;

            var sut = new MovieReadModelGenerator(
                movieRepositoryDouble, theaterReaderStub);

            await sut.Handle(new Envelope(movieCreated));

            Guid movieId = movieCreated.MovieId;

            ScreeningAdded domainEvent = builder
                                         .Build <ScreeningAdded>()
                                         .With(x => x.SourceId, movieId)
                                         .With(x => x.TheaterId, theater.Id)
                                         .With(x => x.SeatRowCount, theater.SeatRowCount)
                                         .With(x => x.SeatColumnCount, theater.SeatColumnCount)
                                         .Create();

            // Act
            await sut.Handle(new Envelope(domainEvent));

            // Assert
            Movie actual = movieRepositoryDouble.Data[movieId];

            actual.Screenings
            .Should().Contain(s => s.Id == domainEvent.ScreeningId).Which
            .Should().BeEquivalentTo(new
            {
                Id = domainEvent.ScreeningId,
                domainEvent.TheaterId,
                TheaterName = theater.Name,
                Seats       =
                    from r in Enumerable.Range(0, theater.SeatRowCount)
                    from c in Enumerable.Range(0, theater.SeatColumnCount)
                    select new Seat
                {
                    Row        = r,
                    Column     = c,
                    IsReserved = false,
                },
                domainEvent.ScreeningTime,
                domainEvent.DefaultFee,
                domainEvent.ChildrenFee,
                CreatedAt = domainEvent.RaisedAt,
            });
        }
        private void AddSomeRandomAddressToTheDatabase(int?count = null, string gazetteer = "Local")
        {
            var number = count ?? _faker.Random.Int(2, 7);

            for (var i = 0; i < number; i++)
            {
                var addressKey    = _faker.Random.String2(14);
                var randomAddress = _fixture.Build <NationalAddress>()
                                    .With(a => a.Gazetteer, gazetteer).Create();
                TestEfDataHelper.InsertAddress(DatabaseContext, addressKey, randomAddress);
            }
        }
        public void Customize(IFixture fixture)
        {
            fixture.Register(() =>
            {
                var payment = fixture
                              .Build <ItPayment>()
                              .Without(x => x.RequiredPaymentId)
                              .Create();

                return(payment);
            });
        }
Exemplo n.º 32
0
        public void GetOneMember_WithValidId_IsNotNull()
        {
            // Arrange
            var id = _fixture.Create <int>();

            var oneMember = _fixture.Build <TeamMemberData>().With(x => x.PersonId, id).Create();

            _teamDatabase.GetOneMember(id).Returns(oneMember);

            var person = _fixture.Create <Person>();

            _personService.GetOnePerson(Arg.Any <int>()).Returns(person);

            _channelFactoryWrapper.GetPersonService().Returns(_personService);

            // Act
            var actual = _sut.GetOneMember(id);

            // Assert
            actual.Should().NotBeNull();
        }
Exemplo n.º 33
0
        public void GlobShouldBeSecret(string json, IFixture fixture)
        {
            var args = fixture.Build <FileArgsBase>()
                       .With(a => a.Prefix, "")
                       .With(a => a.MergeArrays, false)
                       .With(a => a.VariableType, VariableType.EnvironmentGlob)
                       .Create();
            var js   = new VariableConverter(args, Mock.Of <ILogger>());
            var vars = js.Convert(json);

            vars.Single().IsSecret.Should().BeTrue();
        }
Exemplo n.º 34
0
        public void GlobValuesShouldConcat(string json, string expectedValue, IFixture fixture)
        {
            var args = fixture.Build <FileArgsBase>()
                       .With(a => a.Prefix, "")
                       .With(a => a.MergeArrays, false)
                       .With(a => a.VariableType, VariableType.EnvironmentGlob)
                       .Create();
            var js   = new VariableConverter(args, Mock.Of <ILogger>());
            var vars = js.Convert(json);

            vars.Single().Value.Should().Be(expectedValue);
        }
Exemplo n.º 35
0
 public IEnumerable <Scenario> BuildScenarios(int count)
 {
     return(_fixture.Build <Scenario>()
            .Without(p => p.CompletedDateTime)
            .Without(p => p.StartedDateTime)
            .Without(p => p.Progress)
            .With(p => p.IsDefault, false)
            .With(p => p.Passes, () => _passesCoordinator.BuildPasses(1, false).ToList())
            .With(p => p.CampaignPassPriorities, new List <CampaignPassPriorityModel>())
            .With(p => p.DateCreated, DateTime.UtcNow)
            .With(p => p.DateModified, DateTime.UtcNow)
            .CreateMany(count));
 }
Exemplo n.º 36
0
        public void GivenRecurringTask_WhenDateBeforeRange_ShouldNotDoAnything(TimeSpan diffTime)
        {
            // Fixture setup
            var task = _fixture
                       .Build <ArticleScheduleTask>().With(article => article.FreqType, ScheduleFreqTypes.RecurringMonthlyRelative)
                       .Create();

            var startDateTime    = task.StartDate;
            var recurringService = _fixture.Freeze <Mock <IArticleRecurringSchedulerService> >();

            recurringService.Setup(m => m.GetCurrentDBDateTime()).Returns(startDateTime - diffTime);

            var sut = _fixture.Create <RecurringTaskScheduler>();

            // Exercise system
            sut.Run(task);

            // Verify outcome
            recurringService.Verify(f => f.ShowArticle(It.IsAny <int>()), Times.Never());
            recurringService.Verify(f => f.HideArticle(It.IsAny <int>()), Times.Never());
            recurringService.Verify(f => f.HideAndCloseSchedule(It.IsAny <int>()), Times.Never());
        }
Exemplo n.º 37
0
					public static void IdEmptyShouldYieldBadRequest( SpPortalLicenseApi api, IFixture fixture )
					{
						var badTag = fixture.Build<SpPortalLicenseApi.CustomerTag>().With( x => x.Id, Guid.Empty ).CreateAnonymous();

						var response = api.PutCustomerTags( new[] { badTag } );

						Assert.Equal( HttpStatusCode.BadRequest, response.StatusCode );
					}
Exemplo n.º 38
0
					public static void TooLongShouldYieldBadRequest( SpPortalLicenseApi api, IFixture fixture )
					{
						var badTag = fixture.Build<SpPortalLicenseApi.CustomerTag>().With( x => x.Name, new String( 'a', 101 ) ).CreateAnonymous();

						var response = api.PutCustomerTags( new[] { badTag } );

						Assert.Equal( HttpStatusCode.BadRequest, response.StatusCode );
					}
        public void Update_ExistingAdultCustomer_Success_Composed(
            [AsAdultPersisted] Customer e,
            CustomerManager sut,
            IFixture fixture)
        {
            var data = fixture.Build<CustomerUpdate>()
                .With(x => x.ID, e.ID)
                .Create();

            sut.Update(data);
        }
        public void Update_ExistingAdultCustomer_Success(
            //warning: the declaring order of the attrs
            //does not guarantee that customizations will
            //apply in that order, if ordering is required
            //then combine multiple customizations using
            //CompositeCustomizeAttribute like the example
            //below
            [Persisted][AsAdult] Customer e,
            IFixture fixture,
            [Frozen] Mock<ICustomerLogManager> customerLogManager,
            CustomerManager sut)
        {
            var data = fixture.Build<CustomerUpdate>()
                .With(x => x.ID, e.ID)
                .Create();

            sut.Update(data);

            customerLogManager.Verify(x => x.LogUpdate(It.Is<Customer>(c => c.ID == data.ID)));
        }
Exemplo n.º 41
0
 public void Setup()
 {
     _fixture = new Fixture().Customize(new AutoMoqCustomization());
     _sut = _fixture.Build<Configure>().Without(x => x.Container).CreateAnonymous();//.WithVersion_For_Tests();
     _container = _fixture.Freeze<Mock<IContainer>>();
 }
Exemplo n.º 42
0
                public static void DuplicateValuesShouldBeRejected( [Frozen] SpPortalLicenseApi portalApi, RandomLicenseFromListFixture license, ExistingTagsFixture tags, IFixture fixture )
				{
					var validTagValue = tags.Tags
						.Select( ct => fixture.Build<SpPortalLicenseApi.LicenseTag>()
							.With( x => x.Id, ct.Id )
							.CreateAnonymous() )
						.Take( 1 )
						.ToArray();

					var theSameValueTwice = validTagValue.Concat( validTagValue ).ToArray();

					var licenseTagsAssignmentHref = license.Selected._embedded.CustomerTags._links.self.href;
					var apiResult = portalApi.PutLicenseTags( licenseTagsAssignmentHref, theSameValueTwice );
					Assert.Equal( ResponseStatus.Completed, apiResult.ResponseStatus );
					Assert.Equal( HttpStatusCode.InternalServerError, apiResult.StatusCode );
				}
 public void SetUp()
 {
     fixture = new Fixture()
         .Customize(new AutoMoqCustomization());
     pieceBagMock = fixture.Freeze<Mock<IPieceBag>>();
     directionMock = fixture.Freeze<Mock<Direction>>();
     startingPiece = fixture.Build<FakePiece>()
         .With(x => x.Side, Side.Black)
         .Create();
 }
Exemplo n.º 44
0
            public void SetUp()
            {
                fixture = new Fixture()
                    .Customize(new AutoMoqCustomization());
                maximum = fixture.Create<Position>();
                pieceBagMock = fixture.Freeze<Mock<IPieceBag>>();

                piece = fixture.Build<FakePiece>()
                    .With(x => x.Position, new Position(maximum.X - 1, maximum.Y - 1))
                    .Create();

                occupyingPiece = null;
                pieceBagMock.Setup(x => x.GetPiece(piece.Position))
                    .Returns(() => occupyingPiece);

                contiguousOpponentPiecesMock = fixture.Freeze<Mock<IContiguousOpponentPieces>>();
                fixture.Register(() => new Board(maximum, pieceBagMock.Object, contiguousOpponentPiecesMock.Object));
            }