Esempio n. 1
0
        public virtual void before_each()
        {
            autoSubstitute = new AutoSubstitute();

            solutionOpenedStream  = new Subject <SolutionInfo>();
            solutionClosingStream = new Subject <Unit>();
            projectAddedStream    = new Subject <ProjectInfo>();
            projectRemovingtream  = new Subject <ProjectInfo>();

            var solutionNotifier = autoSubstitute.Resolve <ISolutionNotifier>();

            solutionNotifier.SolutionOpenedStream.Returns(solutionOpenedStream);
            solutionNotifier.SolutionClosingStream.Returns(solutionClosingStream);
            solutionNotifier.ProjectAddedStream.Returns(projectAddedStream);
            solutionNotifier.ProjectRemovingtream.Returns(projectRemovingtream);

            projectEnumerator = autoSubstitute.Resolve <IProjectEnumerator>();

            notifier = autoSubstitute.Resolve <ProjectNotifier>();

            testProjectObserver = new TestScheduler().CreateObserver <IEnumerable <ProjectInfo> >();

            subscription = notifier.ProjectStream.Subscribe(testProjectObserver);

            someSolution = new SolutionInfo();

            someProjectInfos = new []
            {
                new ProjectInfo(),
                new ProjectInfo(),
                new ProjectInfo(),
            };
        }
Esempio n. 2
0
        public void SetUp()
        {
            AutoSubstitute _autoSubstitute = new AutoSubstitute();

            //主測試的Pub
            pub = _autoSubstitute.Resolve <Pub>();
            //測試所需要使用的隔離資料
            _autoSubstitute.Resolve <ICheckInFee>().GetFree(Arg.Any <Customer>()).Returns(100);
            _customerList = new List <Customer>
            {
                new Customer {
                    IsMale = true
                },
                new Customer {
                    IsMale = true
                },
                new Customer {
                    IsMale = false
                },
            };

            //使用arg.do 假裝有新增進資料
            _autoSubstitute.Resolve <ICheckInFee>().AddOne(Arg.Do <Customer>(o => _customerList.Add(o)));
            _autoSubstitute.Resolve <ICheckInFee>().Del(Arg.Do <Customer>(o => _customerList.Remove(o)));
        }
Esempio n. 3
0
        public virtual void before_each()
        {
            autoSubstitute = new AutoSubstitute();

            var testBuildManager = autoSubstitute.Resolve <IVsSolutionBuildManager2>();

            uint unregisterToken = VSConstants.VSCOOKIE_NIL;
            uint dummyToken      = 12345;

            testBuildManager.AdviseUpdateSolutionEvents(Arg.Any <IVsUpdateSolutionEvents2>(), out unregisterToken)
            .Returns(callInfo =>
            {
                solutionUpdateEventSink = callInfo.Arg <IVsUpdateSolutionEvents2>();
                callInfo[1]             = dummyToken;

                return(VSConstants.S_OK);
            });

            var solutionBuildManagerProvider = autoSubstitute.Resolve <ISolutionBuildManagerProvider>();

            solutionBuildManagerProvider.Provide().Returns(testBuildManager);

            notifier = autoSubstitute.Resolve <ProjectBuildNotifier>();

            buildObserver = new TestScheduler().CreateObserver <ProjectInfo>();

            subscription = notifier.BuildStream.Subscribe(buildObserver);

            someHierarchy = autoSubstitute.Resolve <IVsHierarchy>();
        }
Esempio n. 4
0
        public void CanSetUserSettings()
        {
            Logger.Debug("CanSetUserSettings");
            var autoResetEvent = new AutoResetEvent(false);

            var inMemoryBlobCache = new InMemoryBlobCache();

            _autoSub.Provide <IBlobCache>(inMemoryBlobCache);

            var dataCache = _autoSub.Resolve <DataCache>();

            dataCache.SetUserSettings(new UserSettings())
            .Subscribe(_ => autoResetEvent.Set());

            autoResetEvent.WaitOne();

            string[] keys = null;

            inMemoryBlobCache.GetAllKeys()
            .Subscribe(enumerable =>
            {
                keys = enumerable.ToArray();
                autoResetEvent.Set();
            });

            autoResetEvent.WaitOne();

            keys.Should().NotBeNull();
            keys.Should().Contain("UserSettings");
        }
Esempio n. 5
0
        public FollowerRoleTests(ITestOutputHelper output)
        {
            var builder = new AutoSubstitute();

            builder.Provide <ILogger>(new TestLogger(output));

            this.volatileState = new VolatileState();
            builder.Provide <IRaftVolatileState>(this.volatileState);

            // Configure settings
            this.settings = builder.Resolve <ISettings>();
            this.settings.ApplyEntriesOnFollowers.Returns(true);
            this.settings.MinElectionTimeoutMilliseconds.Returns(MinElectionTime);
            this.settings.MaxElectionTimeoutMilliseconds.Returns(MaxElectionTime);

            // Rig random number generator to always return the same value.
            this.random = builder.Resolve <IRandom>();
            this.random.Next(Arg.Any <int>(), Arg.Any <int>()).Returns(RiggedRandomResult);

            this.coordinator  = builder.Resolve <IRoleCoordinator <int> >();
            this.stateMachine = builder.Resolve <IStateMachine <int> >();

            this.timers = new MockTimers();
            builder.Provide <RegisterTimerDelegate>(this.timers.RegisterTimer);

            this.persistentState = Substitute.ForPartsOf <InMemoryPersistentState>();
            builder.Provide <IRaftPersistentState>(this.persistentState);

            this.journal = Substitute.ForPartsOf <InMemoryLog <int> >();
            builder.Provide <IPersistentLog <int> >(this.journal);

            // After the container is configured, resolve required services.
            this.role = builder.Resolve <FollowerRole <int> >();
        }
        public static T GetController <T>(this AutoSubstitute autoSubstitute) where T : Controller
        {
            var controller = autoSubstitute.Resolve <T>();

            controller.ControllerContext = autoSubstitute.Resolve <ControllerContext>();
            return(controller);
        }
        public FollowerRoleTests(ITestOutputHelper output)
        {
            var builder = new AutoSubstitute();
            builder.Provide<ILogger>(new TestLogger(output));

            this.volatileState = new VolatileState();
            builder.Provide<IRaftVolatileState>(this.volatileState);

            // Configure settings
            this.settings = builder.Resolve<ISettings>();
            this.settings.ApplyEntriesOnFollowers.Returns(true);
            this.settings.MinElectionTimeoutMilliseconds.Returns(MinElectionTime);
            this.settings.MaxElectionTimeoutMilliseconds.Returns(MaxElectionTime);

            // Rig random number generator to always return the same value.
            this.random = builder.Resolve<IRandom>();
            this.random.Next(Arg.Any<int>(), Arg.Any<int>()).Returns(RiggedRandomResult);

            this.coordinator = builder.Resolve<IRoleCoordinator<int>>();
            this.stateMachine = builder.Resolve<IStateMachine<int>>();

            this.timers = new MockTimers();
            builder.Provide<RegisterTimerDelegate>(this.timers.RegisterTimer);

            this.persistentState = Substitute.ForPartsOf<InMemoryPersistentState>();
            builder.Provide<IRaftPersistentState>(this.persistentState);

            this.journal = Substitute.ForPartsOf<InMemoryLog<int>>();
            builder.Provide<IPersistentLog<int>>(this.journal);

            // After the container is configured, resolve required services.
            this.role = builder.Resolve<FollowerRole<int>>();
        }
Esempio n. 8
0
        private static void RunWithSingleSetupationTest(AutoSubstitute autoSubstitute)
        {
            var component = autoSubstitute.Resolve <TestComponent>();

            component.RunAll();

            autoSubstitute.Resolve <IServiceB>().Received().RunB();
        }
Esempio n. 9
0
        public virtual void before_each()
        {
            autoSubstitute = new AutoSubstitute();

            messageLogger = autoSubstitute.Resolve <IMessageLogger>();

            settings = autoSubstitute.Resolve <IAdapterSettings>();
        }
Esempio n. 10
0
 public void Setup()
 {
     _autoSubstitute = AutoSubstituteContainer.Create();
     _context        = _autoSubstitute.Resolve <ControllerContext>();
     _lookup         = _autoSubstitute.Resolve <ICurtinUserService>();
     DependencyResolver.SetResolver(new AutofacDependencyResolver(_autoSubstitute.Container));
     _httpSimulator = new HttpSimulator().SimulateRequest();
 }
 public void Setup()
 {
     _autoSubstitute = AutoSubstituteContainer.Create();
     _context = _autoSubstitute.Resolve<ControllerContext>();
     _lookup = _autoSubstitute.Resolve<ICurtinUserService>();
     DependencyResolver.SetResolver(new AutofacDependencyResolver(_autoSubstitute.Container));
     _httpSimulator = new HttpSimulator().SimulateRequest();
 }
Esempio n. 12
0
        public virtual void before_each()
        {
            autoSubstitute = new AutoSubstitute();

            testExecutionRecorder = autoSubstitute.Resolve <ITestExecutionRecorder>();

            recorder = autoSubstitute.Resolve <ProgressRecorder>();
        }
Esempio n. 13
0
        public void ProductsByCategory() {
            using(var x = new AutoSubstitute()) 
            {
                var categories = Builder<ProductCategory>.CreateListOfSize(20).BuildList();
                var desiredCategory = Pick.Randomly.From(categories);

                var products = Builder<Product>.CreateListOfSize(200)
                                                    .All()
                                                        .Set(p => p.ProductCategories, () => new[] { Pick.Randomly.From(categories) })
                                                    .ListBuilder
                                                    .BuildList();

                x.Resolve<IRepository<Product>>().TableNoTracking
                                                        .Returns(new EnumerableQuery<Product>(products));

                x.Resolve<ICategories>().FindCatFamily(Arg.Is(desiredCategory.ID))
                                            .Returns(new[] { new BrigitaCategory() { ID = desiredCategory.ID } });
                
                var productService = x.Resolve<BrigitaProducts>();

                
                int pageSize = 20;

                var expectedProducts = products
                                        .Where(p => p.ProductCategories.Any(c => c.ID == desiredCategory.ID))
                                        .OrderBy(p => p.ID);

                int expectedPageCount = expectedProducts.Count() / pageSize + 1;
                
                
                var listPage = productService.GetProductsByCategory(desiredCategory.ID, new ListPageSpec(0, pageSize));

                Assert.AreEqual(expectedPageCount, listPage.PageCount);


                Func<int, int, IEnumerable<IProduct>> fnAggregatePages = null;

                fnAggregatePages = 
                    (i, c) => {
                        var page = productService.GetProductsByCategory(desiredCategory.ID, new ListPageSpec(i++, pageSize)).AsEnumerable();

                        if(i < c) {
                            page = page.Concat(fnAggregatePages(i, c));
                        }

                        return page;
                    };


                var aggregatedProducts = fnAggregatePages(0, expectedPageCount)
                                            .OrderBy(p => p.ID);

                Assert.IsTrue(expectedProducts.SequenceEqual(aggregatedProducts));

                //Try stupid pagespec: what happens? Nothing, hopefully
                Assert.AreEqual(0, productService.GetProductsByCategory(desiredCategory.ID, new ListPageSpec(100, 100)).Count());
            }
        }
 public void Setup()
 {
     _autoSubstitute                   = AutoSubstituteContainer.Create();
     _fieldOfResearchRepository        = _autoSubstitute.Resolve <IFieldOfResearchRepository>();
     _socioEconomicObjectiveRepository = _autoSubstitute.Resolve <ISocioEconomicObjectiveRepository>();
     _controller               = _autoSubstitute.GetController <AjaxController>();
     _lookupService            = _autoSubstitute.Resolve <ICurtinUserService>();
     _dataCollectionRepository = _autoSubstitute.Resolve <IDataCollectionRepository>();
 }
 public void Setup()
 {
     _autoSubstitute = AutoSubstituteContainer.Create();
     _fieldOfResearchRepository = _autoSubstitute.Resolve<IFieldOfResearchRepository>();
     _socioEconomicObjectiveRepository = _autoSubstitute.Resolve<ISocioEconomicObjectiveRepository>();
     _controller = _autoSubstitute.GetController<AjaxController>();
     _lookupService = _autoSubstitute.Resolve<ICurtinUserService>();
     _dataCollectionRepository = _autoSubstitute.Resolve<IDataCollectionRepository>();
 }
        public CandidateRoleTests(ITestOutputHelper output)
        {
            var builder =
                new AutoSubstitute(cb => cb.Register(_ => Substitute.For<IRaftGrain<int>>()).InstancePerDependency());
            builder.Provide<ILogger>(new TestLogger(output));

            this.volatileState = new VolatileState();
            builder.Provide<IRaftVolatileState>(this.volatileState);

            // Configure settings
            this.settings = builder.Resolve<ISettings>();
            this.settings.MinElectionTimeoutMilliseconds.Returns(MinElectionTime);
            this.settings.MaxElectionTimeoutMilliseconds.Returns(MaxElectionTime);

            // Rig random number generator to always return the same value.
            this.random = builder.Resolve<IRandom>();
            this.random.Next(Arg.Any<int>(), Arg.Any<int>()).Returns(RiggedRandomResult);

            this.coordinator = builder.Resolve<IRoleCoordinator<int>>();
            this.coordinator.StepDownIfGreaterTerm(Arg.Any<IMessage>())
                .Returns(
                    info => Task.FromResult(((IMessage)info[0]).Term > this.persistentState.CurrentTerm));
            var currentRole = builder.Resolve<IRaftRole<int>>();
            currentRole.RequestVote(Arg.Any<RequestVoteRequest>())
                .Returns(Task.FromResult(new RequestVoteResponse { Term = 1, VoteGranted = true }));
            currentRole.Append(Arg.Any<AppendRequest<int>>())
                .Returns(Task.FromResult(new AppendResponse { Term = 1, Success = true }));
            this.coordinator.Role.Returns(currentRole);

            this.timers = new MockTimers();
            builder.Provide<RegisterTimerDelegate>(this.timers.RegisterTimer);

            this.persistentState = Substitute.ForPartsOf<InMemoryPersistentState>();
            builder.Provide<IRaftPersistentState>(this.persistentState);

            this.journal = Substitute.ForPartsOf<InMemoryLog<int>>();
            builder.Provide<IPersistentLog<int>>(this.journal);

            this.identity = Substitute.For<IServerIdentity>();
            this.identity.Id.Returns(Guid.NewGuid().ToString());
            builder.Provide(this.identity);

            this.members = builder.Resolve<StaticMembershipProvider>();
            this.members.SetServers(new[] { this.identity.Id, "other1", "other2", "other3", "other4" });
            builder.Provide<IMembershipProvider>(this.members);

            this.grainFactory = new FakeGrainFactory(builder.Container);
            builder.Provide<IGrainFactory>(this.grainFactory);
            this.OnRaftGrainCreated =
                (id, grain) =>
                grain.RequestVote(Arg.Any<RequestVoteRequest>())
                    .Returns(Task.FromResult(new RequestVoteResponse { VoteGranted = true }));

            // After the container is configured, resolve required services.
            this.role = builder.Resolve<CandidateRole<int>>();
            this.container = builder;
        }
 public void Setup()
 {
     _autoSubstitute = AutoSubstituteContainer.Create();
     _context        = _autoSubstitute.Resolve <ControllerContext>();
     DependencyResolver.SetResolver(new AutofacDependencyResolver(_autoSubstitute.Container));
     _httpSimulator            = new HttpSimulator().SimulateRequest();
     _form                     = _context.HttpContext.Request.Form;
     _dataCollectionRepository = _autoSubstitute.Resolve <IDataCollectionRepository>();
 }
 public void Setup()
 {
     _autoSubstitute = AutoSubstituteContainer.Create();
     _context = _autoSubstitute.Resolve<ControllerContext>();
     DependencyResolver.SetResolver(new AutofacDependencyResolver(_autoSubstitute.Container));
     _httpSimulator = new HttpSimulator().SimulateRequest();
     _form = _context.HttpContext.Request.Form;
     _dataCollectionRepository = _autoSubstitute.Resolve<IDataCollectionRepository>();
 }
Esempio n. 19
0
        public void AddImageToAlbum()
        {
            var directoryPath = Faker.System.DirectoryPathWindows();
            var directory     = new Directory
            {
                Id     = Faker.Random.Int(1),
                Path   = directoryPath,
                Images = new List <Image>()
            };

            var images = Faker.Make(Faker.Random.Int(3, 5), () => new Image
            {
                Path        = Path.Join(directoryPath) + Faker.System.FileName("jpg"),
                DirectoryId = directory.Id
            });

            directory.Images.AddRange(images);

            var unitOfWork = Substitute.For <IUnitOfWork>();

            unitOfWork.DirectoryRepository.Get()
            .ReturnsForAnyArgs(new[] { directory, FakerProfiles.FakeNewDirectory });

            _unitOfWorkQueue.Enqueue(unitOfWork);

            var autoResetEvent = new AutoResetEvent(false);

            var imageManagementService = _autoSubstitute.Resolve <ImageManagementService>();

            var albumName = Faker.Random.Words(2);
            var albumId   = Faker.Random.Int(1);

            unitOfWork.AlbumRepository.Get().ReturnsForAnyArgs(new[] { new Album {
                                                                           Id = albumId, Name = albumName
                                                                       } });

            unitOfWork.ImageRepository.GetById(Arg.Any <int>())
            .ReturnsForAnyArgs(info =>
            {
                return(images.First(i => i.Id == (int)info.Arg <object>()));
            });

            imageManagementService.AddImagesToAlbum(albumId, images.Select(image => image.Id))
            .Subscribe(unit => autoResetEvent.Set());

            _testSchedulerProvider.TaskPool.AdvanceBy(1);

            autoResetEvent.WaitOne(10).Should().BeTrue();

            unitOfWork.AlbumImageRepository.ReceivedWithAnyArgs(images.Count)
            .Insert(null);

            unitOfWork.Received(1).Save();

            unitOfWork.Received(1).Dispose();
        }
        public virtual void before_each()
        {
            autoSubstitute = new AutoSubstitute();

            contextFinder = autoSubstitute.Resolve <IContextFinder>();

            runnableContextFinder = autoSubstitute.Resolve <RunnableContextFinder>();

            contextFinder.BuildContextCollection(somePath).Returns(someContextCollection);
        }
 public void SetUp()
 {
     _autoSubstitute    = AutoSubstituteContainer.Create();
     _controller        = _autoSubstitute.GetController <DmpController>();
     _projectRepository = _autoSubstitute.Resolve <IProjectRepository>();
     _timerRepository   = _autoSubstitute.Resolve <ITimerRepository>();
     _context           = _autoSubstitute.Resolve <ControllerContext>();
     _form   = _context.HttpContext.Request.Form;
     _lookup = _autoSubstitute.Resolve <ICurtinUserService>();
 }
Esempio n. 22
0
        public virtual void before_each()
        {
            autoSubstitute = new AutoSubstitute();

            progressRecorder = autoSubstitute.Resolve <IProgressRecorder>();

            executedExampleMapper = autoSubstitute.Resolve <IExecutedExampleMapper>();

            reporter = autoSubstitute.Resolve <ExecutionReporter>();
        }
 public void SetUp()
 {
     _autoSubstitute = AutoSubstituteContainer.Create();
     _controller = _autoSubstitute.GetController<ApprovalController>();
     _dataCollectionRepository = _autoSubstitute.Resolve<IDataCollectionRepository>();
     _hashCodeRepository = _autoSubstitute.Resolve<IDataCollectionHashCodeRepository>();
     _lookup = _autoSubstitute.Resolve<ICurtinUserService>();
     _bus = _autoSubstitute.Resolve<IBus>();
     _projectRepository = _autoSubstitute.Resolve<IProjectRepository>();
 }
 public void SetUp()
 {
     _autoSubstitute = AutoSubstituteContainer.Create();
     _controller = _autoSubstitute.GetController<DmpController>();
     _projectRepository = _autoSubstitute.Resolve<IProjectRepository>();
     _timerRepository = _autoSubstitute.Resolve<ITimerRepository>();
     _context = _autoSubstitute.Resolve<ControllerContext>();
     _form = _context.HttpContext.Request.Form;
     _lookup = _autoSubstitute.Resolve<ICurtinUserService>();
 }
Esempio n. 25
0
        public void DeleteTrail_Just_Works()
        {
            var autoSub = new AutoSubstitute();

            var trailsRepo = autoSub.Resolve <ITrailsRepository>();

            trailsRepo.DeleteTrail(Arg.Any <int>());

            autoSub.Resolve <TrailsService>().DeleteTrail(1);
        }
Esempio n. 26
0
        public void UpdateTrail_Just_Works()
        {
            var autoSub = new AutoSubstitute();

            var trailsRepo = autoSub.Resolve <ITrailsRepository>();

            trailsRepo.UpdateTrail(Arg.Any <int>(), Arg.Any <Trail>());

            autoSub.Resolve <TrailsService>().UpdateTrail(1, new Trail());
        }
Esempio n. 27
0
 public void SetUp()
 {
     _autoSubstitute           = AutoSubstituteContainer.Create();
     _controller               = _autoSubstitute.GetController <ApprovalController>();
     _dataCollectionRepository = _autoSubstitute.Resolve <IDataCollectionRepository>();
     _hashCodeRepository       = _autoSubstitute.Resolve <IDataCollectionHashCodeRepository>();
     _lookup            = _autoSubstitute.Resolve <ICurtinUserService>();
     _bus               = _autoSubstitute.Resolve <IBus>();
     _projectRepository = _autoSubstitute.Resolve <IProjectRepository>();
 }
Esempio n. 28
0
        public void ByDefaultConcreteTypesAreResolvedToTheSameSharedInstance()
        {
            using (var fake = new AutoSubstitute())
            {
                var baz1 = fake.Resolve <Baz>();
                var baz2 = fake.Resolve <Baz>();

                Assert.Same(baz1, baz2);
            }
        }
 public void SetUp()
 {
     _autoSubstitute = AutoSubstituteContainer.Create();
     _controller = _autoSubstitute.GetController<DataDepositController>();
     _confirmController = _autoSubstitute.GetController<ConfirmController>();
     _projectController = _autoSubstitute.GetController<ProjectController>();
     _context = _autoSubstitute.Resolve<ControllerContext>();
     _lookup = _autoSubstitute.Resolve<ICurtinUserService>();
     _projectRepository = _autoSubstitute.Resolve<IProjectRepository>();
 }
Esempio n. 30
0
 public void SetUp()
 {
     _autoSubstitute    = AutoSubstituteContainer.Create();
     _controller        = _autoSubstitute.GetController <DataDepositController>();
     _confirmController = _autoSubstitute.GetController <ConfirmController>();
     _projectController = _autoSubstitute.GetController <ProjectController>();
     _context           = _autoSubstitute.Resolve <ControllerContext>();
     _lookup            = _autoSubstitute.Resolve <ICurtinUserService>();
     _projectRepository = _autoSubstitute.Resolve <IProjectRepository>();
 }
 public void Setup()
 {
     _autoSubstitute           = AutoSubstituteContainer.Create();
     _projectRepository        = _autoSubstitute.Resolve <IProjectRepository>();
     _dataCollectionRepository = _autoSubstitute.Resolve <IDataCollectionRepository>();
     _controller = _autoSubstitute.GetController <AdminController>();
     _context    = _autoSubstitute.Resolve <ControllerContext>();
     _form       = _context.HttpContext.Request.Form;
     _csvHelper  = _autoSubstitute.Resolve <ICsvHelper>();
 }
        public void WhenConfiguringTentacle_ThenTheCorrectCommandsShouldBeSentToTentacleExe()
        {
            var b = new StringBuilder();

            _container.Resolve <IProcessRunner>().WhenForAnyArgs(r => r.Run(null, null)).Do(a => b.AppendLine(string.Format("{0} {1}", a[0], a[1])));

            _sut.ConfigureTentacle();

            Approvals.Verify(b.ToString());
        }
 public void Setup()
 {
     _autoSubstitute = AutoSubstituteContainer.Create();
     _projectRepository = _autoSubstitute.Resolve<IProjectRepository>();
     _dataCollectionRepository = _autoSubstitute.Resolve<IDataCollectionRepository>();
     _controller = _autoSubstitute.GetController<AdminController>();
     _context = _autoSubstitute.Resolve<ControllerContext>();
     _form = _context.HttpContext.Request.Form;
     _csvHelper = _autoSubstitute.Resolve<ICsvHelper>();
 }
        public static void ShouldResolveASubstituteForIndexedDependency()
        {
            var autoSubstitute = new AutoSubstitute();
            var index = autoSubstitute.Resolve<IIndex<Switch, IDependency2>>();
            index[Switch.On].SomeOtherMethod().Returns(5);

            var target = autoSubstitute.Resolve<ClassWithKeyedDependencies>();

            Assert.That(target.OnDependency.SomeOtherMethod(), Is.EqualTo(5));
        }
Esempio n. 35
0
        public void ByDefaultAbstractTypesAreResolvedToTheSameSharedInstance()
        {
            using (var fake = new AutoSubstitute())
            {
                var bar1 = fake.Resolve <IBar>();
                var bar2 = fake.Resolve <IBar>();

                Assert.Same(bar1, bar2);
            }
        }
Esempio n. 36
0
        public LeaderRoleTests(ITestOutputHelper output)
        {
            var builder =
                new AutoSubstitute(cb => cb.Register(_ => Substitute.For <IRaftGrain <int> >()).InstancePerDependency());

            builder.Provide <ILogger>(new TestLogger(output));

            this.volatileState = new VolatileState();
            builder.Provide <IRaftVolatileState>(this.volatileState);

            this.coordinator = builder.Resolve <IRoleCoordinator <int> >();
            this.coordinator.StepDownIfGreaterTerm(Arg.Any <IMessage>())
            .Returns(
                info => Task.FromResult(((IMessage)info[0]).Term > this.persistentState.CurrentTerm));
            var currentRole = builder.Resolve <IRaftRole <int> >();

            currentRole.RequestVote(Arg.Any <RequestVoteRequest>())
            .Returns(Task.FromResult(new RequestVoteResponse {
                Term = 1, VoteGranted = true
            }));
            currentRole.Append(Arg.Any <AppendRequest <int> >())
            .Returns(Task.FromResult(new AppendResponse {
                Term = 1, Success = true
            }));
            this.coordinator.Role.Returns(currentRole);

            this.timers = new MockTimers();
            builder.Provide <RegisterTimerDelegate>(this.timers.RegisterTimer);

            this.persistentState = Substitute.ForPartsOf <InMemoryPersistentState>();
            builder.Provide <IRaftPersistentState>(this.persistentState);

            this.journal = Substitute.ForPartsOf <InMemoryLog <int> >();
            builder.Provide <IPersistentLog <int> >(this.journal);

            this.identity = Substitute.For <IServerIdentity>();
            this.identity.Id.Returns(Guid.NewGuid().ToString());
            builder.Provide(this.identity);

            this.members = builder.Resolve <StaticMembershipProvider>();
            this.members.SetServers(new[] { this.identity.Id, "other1", "other2", "other3", "other4" });
            builder.Provide <IMembershipProvider>(this.members);

            this.grainFactory = new FakeGrainFactory(builder.Container);
            builder.Provide <IGrainFactory>(this.grainFactory);
            this.OnRaftGrainCreated =
                (id, grain) =>
                grain.RequestVote(Arg.Any <RequestVoteRequest>())
                .Returns(Task.FromResult(new RequestVoteResponse {
                VoteGranted = true
            }));

            // After the container is configured, resolve required services.
            this.role = builder.Resolve <LeaderRole <int> >();
        }
Esempio n. 37
0
        public static void ShouldResolveASubstituteForIndexedDependency()
        {
            var autoSubstitute = new AutoSubstitute();
            var index          = autoSubstitute.Resolve <IIndex <Switch, IDependency2> >();

            index[Switch.On].SomeOtherMethod().Returns(5);

            var target = autoSubstitute.Resolve <ClassWithKeyedDependencies>();

            Assert.Equal(target.OnDependency.SomeOtherMethod(), 5);
        }
        public virtual void before_each()
        {
            autoSubstitute = new AutoSubstitute();

            repository = autoSubstitute.Resolve <SettingsRepository>();

            discoveryContext = autoSubstitute.Resolve <IDiscoveryContext>();
            runSettings      = autoSubstitute.Resolve <IRunSettings>();

            discoveryContext.RunSettings.Returns(runSettings);
        }
Esempio n. 39
0
        public void Example_test_with_standard_resolve()
        {
            const int val            = 3;
            var       AutoSubstitute = new AutoSubstitute();

            AutoSubstitute.Resolve <IDependency2>().SomeOtherMethod().Returns(val);
            AutoSubstitute.Resolve <IDependency1>().SomeMethod(val).Returns(c => c.Arg <int>());

            var result = AutoSubstitute.Resolve <MyClass>().AMethod();

            Assert.That(result, Is.EqualTo(val));
        }
Esempio n. 40
0
        public virtual void before_each()
        {
            autoSubstitute = new AutoSubstitute();

            var testBinaryNotifier = autoSubstitute.Resolve <ITestBinaryNotifier>();

            testDllPathStream = new Subject <IEnumerable <string> >();
            testBinaryNotifier.PathStream.Returns(testDllPathStream);

            containerFactory = autoSubstitute.Resolve <ITestContainerFactory>();

            containerDiscoverer = new NSpecTestContainerDiscoverer(testBinaryNotifier, containerFactory);
        }
 public void SetUp()
 {
     const string payload = @"<link href='global.css' type='text/css' /><div>Hello World</div>";
     _account = 1470;
     _item = 7418569;
     _autoSubstitute = AutoSubstituteContainer.Create();
     _appSettingsService = _autoSubstitute.Resolve<IAppSettingsService>();
     _simpleWebRequestService = _autoSubstitute.Resolve<ISimpleWebRequestService>();
     _simpleWebRequestService.GetResponseText(Arg.Any<string>()).Returns(payload);
     var libGuideService = new LibGuideService(_simpleWebRequestService, _appSettingsService);
     _autoSubstitute.Provide<ILibGuideService>(libGuideService);
     _controller = _autoSubstitute.Resolve<LibGuideController>();
 }
Esempio n. 42
0
        public void Example_test_with_concrete_object_provided()
        {
            const int val1           = 3;
            const int val2           = 2;
            var       AutoSubstitute = new AutoSubstitute();

            AutoSubstitute.Resolve <IDependency2>().SomeOtherMethod().Returns(val1);
            AutoSubstitute.Provide(new ConcreteClass(val2));

            var result = AutoSubstitute.Resolve <MyClassWithConcreteDependency>().AMethod();

            Assert.That(result, Is.EqualTo(val1 + val2));
        }
 public static void Unauthenticated(AutoSubstitute autoSubstitute)
 {
     var principal = autoSubstitute.Resolve<HttpContextBase>().User;
     principal.Identity.Name.Returns(string.Empty);
     principal.Identity.IsAuthenticated.Returns(false);
     principal.IsInRole(Arg.Any<string>()).ReturnsForAnyArgs(false);
 }
 public static void AuthenticatedAs(AutoSubstitute autoSubstitute, string username, params string[] roles)
 {
     var principal = autoSubstitute.Resolve<HttpContextBase>().User;
     principal.Identity.Name.Returns(username);
     principal.Identity.IsAuthenticated.Returns(true);
     roles.Do(r => principal.IsInRole(r).Returns(true));
 }
 public OctopusDeployTests()
 {
     _container = new AutoSubstitute();
     _config = new ConfigSettings(s => string.Format("%{0}%", s), s => string.Format("c:\\{0}", s));
     _container.Provide(_config);
     _container.Provide(MachineName);
     _sut = _container.Resolve<OctopusDeploy.Infrastructure.OctopusDeploy>();
 }
Esempio n. 46
0
 public void Setup()
 {
     _autoSubstitute = AutoSubstituteContainer.Create();
     _h = _autoSubstitute.ResolveAndSubstituteFor<HtmlHelper<TestFieldViewModel>>();
     _t = _autoSubstitute.Resolve<IFormTemplate>();
     _t.BeginForm(Action, Method, _htmlAttributes, Enctype).Returns(_beginHtml);
     _t.EndForm().Returns(_endHtml);
 }
        public static void ShouldResolveIndexedDependencies()
        {
            var autoSubstitute = new AutoSubstitute();

            var target = autoSubstitute.Resolve<ClassWithKeyedDependencies>();

            Assert.NotNull(target.OnDependency);
            Assert.NotNull(target.OffDependency);
        }
        public void SetUp()
        {
            _autoSubstitute = AutoSubstituteContainer.Create();
            
            var appSettings = _autoSubstitute.Resolve<IAppSettingsService>();
            appSettings.LdapUri.Returns(@"LDAP://...");
            appSettings.LdapUser.Returns(@"query");
            appSettings.LdapPassword.Returns("abcdef");

            var directoryEntry = _autoSubstitute.Resolve<IDirectoryEntryService>();
            directoryEntry.GetGroupMembership(Arg.Any<string>(),Arg.Any<string>(),Arg.Any<string>(),Arg.Any<string>())
				.Returns(new[] { "Secondary-Approver" });

            var dependencyResolver = _autoSubstitute.Resolve<IDependencyResolver>();
            DependencyResolver.SetResolver(dependencyResolver);
            dependencyResolver.GetService<IAppSettingsService>().Returns(appSettings);
            dependencyResolver.GetService<IDirectoryEntryService>().Returns(directoryEntry);

        }
        public static void ShouldAcceptProvidedIndexedDependency()
        {
            var autoSubstitute = new AutoSubstitute();
            var substitute = Substitute.For<IDependency2>();
            substitute.SomeOtherMethod().Returns(5);
            autoSubstitute.Provide(substitute, Switch.On);
            
            var target = autoSubstitute.Resolve<ClassWithKeyedDependencies>();

            Assert.That(target.OnDependency.SomeOtherMethod(), Is.EqualTo(5));
        }
        public RoleCoordinatorTests(ITestOutputHelper output)
        {
            var builder = new AutoSubstitute();
            builder.Provide<ILogger>(new TestLogger(output));

            this.persistentState = Substitute.ForPartsOf<InMemoryPersistentState>();
            builder.Provide<IRaftPersistentState>(this.persistentState);

            builder.ResolveAndSubstituteFor<FollowerRole<int>>();

            // After the container is configured, resolve required services.
            this.coordinator = builder.Resolve<RoleCoordinator<int>>();
            this.container = builder;
        }
 public void SetUp()
 {
     _autoSubstitute = AutoSubstituteContainer.Create();
     _controller = _autoSubstitute.GetController<DataCollectionController>();
     _projectRepository = _autoSubstitute.Resolve<IProjectRepository>();
     _dataCollectionRepository = _autoSubstitute.Resolve<IDataCollectionRepository>();
     _context = _autoSubstitute.Resolve<ControllerContext>();
     _form = _context.HttpContext.Request.Form;
     _lookup = _autoSubstitute.Resolve<ICurtinUserService>();
     _fieldOfResearchRepository = _autoSubstitute.Resolve<IFieldOfResearchRepository>();
     _socioEconomicObjectiveRepository = _autoSubstitute.Resolve<ISocioEconomicObjectiveRepository>();
     _bus = _autoSubstitute.Resolve<IBus>();
 }
        public void SetUp()
        {
            _autoSubstitute = AutoSubstituteContainer.Create();
            _controller = _autoSubstitute.GetController<ProjectController>();
            _dmpController = _autoSubstitute.GetController<DmpController>();
            _projectRepository = _autoSubstitute.Resolve<IProjectRepository>();
            _context = _autoSubstitute.Resolve<ControllerContext>();
            _form = _context.HttpContext.Request.Form;
            _lookup = _autoSubstitute.Resolve<ICurtinUserService>();
            _fieldOfResearchRepository = _autoSubstitute.Resolve<IFieldOfResearchRepository>();
            _socioEconomicObjectiveRepository = _autoSubstitute.Resolve<ISocioEconomicObjectiveRepository>();

            var appSettings = _autoSubstitute.Resolve<IAppSettingsService>();
            var dependencyResolver = _autoSubstitute.Resolve<IDependencyResolver>();
            DependencyResolver.SetResolver(dependencyResolver);
            dependencyResolver.GetService<IAppSettingsService>().Returns(appSettings);
        }
        public void Example_test_with_substitute_for_concrete_resolved_from_autofac()
        {
            const int val1 = 2;
            const int val2 = 3;
            const int val3 = 4;
            var AutoSubstitute = new AutoSubstitute();
            // Much better / more maintainable than:
            //AutoSubstitute.SubstituteFor<ConcreteClassWithDependency>(AutoSubstitute.Resolve<IDependency1>(), val1);
            AutoSubstitute.ResolveAndSubstituteFor<ConcreteClassWithDependency>(new TypedParameter(typeof(int), val1));
            AutoSubstitute.Resolve<IDependency2>().SomeOtherMethod().Returns(val2);
            AutoSubstitute.Resolve<IDependency1>().SomeMethod(val1).Returns(val3);

            var result = AutoSubstitute.Resolve<MyClassWithConcreteDependencyThatHasDependencies>().AMethod();

            Assert.That(result, Is.EqualTo(val2*val3*2));
        }
        public void Example_test_with_substitute_for_concrete()
        {
            const int val1 = 3;
            const int val2 = 2;
            const int val3 = 10;
            var AutoSubstitute = new AutoSubstitute();
            AutoSubstitute.Resolve<IDependency2>().SomeOtherMethod().Returns(val1);
            AutoSubstitute.SubstituteFor<ConcreteClass>(val2).Add(Arg.Any<int>()).Returns(val3);

            var result = AutoSubstitute.Resolve<MyClassWithConcreteDependency>().AMethod();

            Assert.That(result, Is.EqualTo(val3));
        }
        public void SetUp()
        {
            _autoSubstitute = AutoSubstituteContainer.Create();

            _projectRepository = _autoSubstitute.Resolve<IProjectRepository>();
            _dataCollectionRepository = _autoSubstitute.Resolve<IDataCollectionRepository>();
            _controller = _autoSubstitute.GetController<ConfirmController>();
            _lookup = _autoSubstitute.Resolve<ICurtinUserService>();
            var user = CreateUser("XX12345");
            var dmp = Builder<DataManagementPlan>.CreateNew()
                .With(o => o.NewDataDetail = Builder<NewDataDetail>.CreateNew().Build())
                .And(o => o.ExistingDataDetail = Builder<ExistingDataDetail>.CreateNew().Build())
                .And(o => o.DataSharing = Builder<DataSharing>.CreateNew().Build())
                .And(o => o.DataRelationshipDetail = Builder<DataRelationshipDetail>.CreateNew().Build())
                .Build();
            var dd = Builder<DataDeposit>.CreateNew().Build();
            _project = Builder<Project>.CreateNew()
                .With(o => o.DataManagementPlan = dmp)
                .And(o => o.DataDeposit = dd)
                .And(p => p.Description = "TestProject")
                .And(o => o.Keywords = "1,2,3,4,5,6,7,8,9,10,11,12")
                .Build();
            _project.FieldsOfResearch.AddRange(Builder<ProjectFieldOfResearch>
                                                   .CreateListOfSize(5)
                                                   .All()
                                                   .With(p => p.FieldOfResearch = Builder<FieldOfResearch>.CreateNew().Build())
                                                   .Build());
            _project.SocioEconomicObjectives.AddRange(Builder<ProjectSocioEconomicObjective>
                                                          .CreateListOfSize(7)
                                                          .All()
                                                          .With(p => p.SocioEconomicObjective = Builder<SocioEconomicObjective>.CreateNew().Build())
                                                          .Build());
            _project.Parties.AddRange(Builder<ProjectParty>.CreateListOfSize(8)
                                          .TheFirst(1)
                                          .With(o => o.Role = AccessRole.Members)
                                          .And(o => o.Party = Builder<Party>.CreateNew().With(p => p.Id = 0).Build())
                                          .TheNext(1)
                                          .With(o => o.Role = AccessRole.Owners)
                                          .And(o => o.Party = Builder<Party>.CreateNew().With(p => p.Id = 0).And(p => p.UserId = user.CurtinId).Build())
                                          .And(o => o.Relationship = ProjectRelationship.PrincipalInvestigator)
                                          .TheNext(1)
                                          .With(o => o.Role = AccessRole.Visitors)
                                          .And(o => o.Party = Builder<Party>.CreateNew().With(p => p.Id = 0).Build())
                                          .TheNext(1)
                                          .With(o => o.Role = AccessRole.None)
                                          .And(o => o.Party = Builder<Party>.CreateNew().With(p => p.Id = 0).Build())
                                          .TheNext(1)
                                          .With(o => o.Role = AccessRole.Members)
                                          .And(
                                              o =>
                                              o.Party =
                                              Builder<Party>.CreateNew().With(p => p.UserId = "FF24587").Build())
                                          .TheNext(1)
                                          .With(o => o.Role = AccessRole.Visitors)
                                          .And(
                                              o =>
                                              o.Party =
                                              Builder<Party>.CreateNew().With(p => p.UserId = "GA37493").Build())
                                          .TheNext(1)
                                          .With(o => o.Role = AccessRole.None)
                                          .And(
                                              o =>
                                              o.Party =
                                              Builder<Party>.CreateNew().With(p => p.UserId = "KK25344").Build())
                                          .TheNext(1)
                                          .With(o => o.Role = AccessRole.Owners)
                                          .And(
                                              o =>
                                              o.Party =
                                              Builder<Party>.CreateNew().With(p => p.UserId = "DD25265").Build())
                                          .Build());

            _bus = _autoSubstitute.Resolve<IBus>();
            _projectRepository.Get(Arg.Is(_project.Id)).Returns(_project);
            _projectRepository.GetByDataManagementPlanId(Arg.Is(_project.DataManagementPlan.Id)).Returns(_project);

            var resolver = Substitute.For<IDependencyResolver>();
            DependencyResolver.SetResolver(resolver);
        }
        public void Example_test_with_concrete_object_provided()
        {
            const int val1 = 3;
            const int val2 = 2;
            var AutoSubstitute = new AutoSubstitute();
            AutoSubstitute.Resolve<IDependency2>().SomeOtherMethod().Returns(val1);
            AutoSubstitute.Provide(new ConcreteClass(val2));

            var result = AutoSubstitute.Resolve<MyClassWithConcreteDependency>().AMethod();

            Assert.That(result, Is.EqualTo(val1 + val2));
        }
 public void SetUp()
 {
     _autoSubstitute = AutoSubstituteContainer.Create();
     _controller = _autoSubstitute.GetController<BaseController>();
     _lookup = _autoSubstitute.Resolve<ICurtinUserService>();
 }
        public void Example_test_with_standard_resolve()
        {
            const int val = 3;
            var AutoSubstitute = new AutoSubstitute();
            AutoSubstitute.Resolve<IDependency2>().SomeOtherMethod().Returns(val);
            AutoSubstitute.Resolve<IDependency1>().SomeMethod(val).Returns(c => c.Arg<int>());

            var result = AutoSubstitute.Resolve<MyClass>().AMethod();

            Assert.That(result, Is.EqualTo(val));
        }
        public void Example_test_with_concrete_type_provided()
        {
            const int val = 3;
            var AutoSubstitute = new AutoSubstitute();
            AutoSubstitute.Resolve<IDependency2>().SomeOtherMethod().Returns(val); // This shouldn't do anything because of the next line
            AutoSubstitute.Provide<IDependency2, Dependency2>();
            AutoSubstitute.Resolve<IDependency1>().SomeMethod(Arg.Any<int>()).Returns(c => c.Arg<int>());

            var result = AutoSubstitute.Resolve<MyClass>().AMethod();

            Assert.That(result, Is.EqualTo(Dependency2.Value));
        }