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 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 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>();
 }
 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;
 }
Exemplo n.º 6
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 void Setup()
 {
     _autoSubstitute = AutoSubstituteContainer.Create();
     _context = _autoSubstitute.Resolve<ControllerContext>();
     _lookup = _autoSubstitute.Resolve<ICurtinUserService>();
     DependencyResolver.SetResolver(new AutofacDependencyResolver(_autoSubstitute.Container));
     _httpSimulator = new HttpSimulator().SimulateRequest();
 }
Exemplo n.º 8
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 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 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();
     _fieldOfResearchRepository = _autoSubstitute.Resolve<IFieldOfResearchRepository>();
     _socioEconomicObjectiveRepository = _autoSubstitute.Resolve<ISocioEconomicObjectiveRepository>();
     _controller = _autoSubstitute.GetController<AjaxController>();
     _lookupService = _autoSubstitute.Resolve<ICurtinUserService>();
     _dataCollectionRepository = _autoSubstitute.Resolve<IDataCollectionRepository>();
 }
        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));
        }
 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>();
 }
 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();
     _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 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 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));
        }
Exemplo n.º 18
0
    public void Handle_Three_Substitute_Item()
    {
        var fake1 = AutoSubstitute.Provide(NSubstitute.Substitute.For <Item>());
        var fake2 = AutoSubstitute.Provide(NSubstitute.Substitute.For <Item>());
        var fake3 = AutoSubstitute.Provide(NSubstitute.Substitute.For <Item>());

        var result = AutoSubstitute.Resolve <IEnumerable <Item> >().ToArray();

        result.Should().HaveCount(3);
        result.Should().Contain(fake1);
        result.Should().Contain(fake2);
        result.Should().Contain(fake3);
    }
        public void TestIListCorrectlyResolves()
        {
            using var autosub = AutoSubstitute.Configure()
                                .Provide <IServiceItem, ServiceItemA>(out var mockA)
                                .Provide <IServiceItem, ServiceItemB>(out var mockB)
                                .Build();

            var component = autosub.Resolve <TestIListComponent>();

            Assert.That(component.ServiceItems, Is.Not.Empty);
            Assert.That(component.ServiceItems.Contains(mockA.Value), Is.True);
            Assert.That(component.ServiceItems.Contains(mockB.Value), Is.True);
        }
        public void TestIEnumerableCorrectlyResolves()
        {
            using (var autosub = new AutoSubstitute())
            {
                var mockA     = autosub.Provide <IServiceItem, ServiceItemA>();
                var mockB     = autosub.Provide <IServiceItem, ServiceItemB>();
                var component = autosub.Resolve <TestIEnumerableComponent>();

                Assert.That(component.ServiceItems, Is.Not.Empty);
                Assert.That(component.ServiceItems.Contains(mockA), Is.True);
                Assert.That(component.ServiceItems.Contains(mockB), Is.True);
            }
        }
        public void InjectPropertiesInterfaceWithUnregisteredPerLifetime()
        {
            using var mock = AutoSubstitute.Configure()
                             .InjectProperties()
                             .MakeUnregisteredTypesPerLifetime()
                             .Build()
                             .Container;

            var class1         = mock.Resolve <Class1>();
            var testInterface1 = mock.Resolve <ITestInterface1>();

            Assert.AreSame(class1, testInterface1.Instance);
        }
        public void CustomContainerBuilder()
        {
            var container = Substitute.For <IContainer>();

            using var mock = AutoSubstitute.Configure()
                             .ConfigureOptions(options =>
            {
                options.BuildContainerFactory = _ => container;
            })
                             .Build();

            Assert.AreSame(container, mock.Container);
        }
Exemplo n.º 23
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 void Should_Return_Empty_Descriptor()
        {
            // Given
            var handlerDescriptors = Enumerable.Empty <ILspHandlerDescriptor>();

            var handlerMatcher = AutoSubstitute.Resolve <TextDocumentMatcher>();

            // When
            var result = handlerMatcher.FindHandler(1, handlerDescriptors);

            // Then
            result.Should().BeEmpty();
        }
Exemplo n.º 25
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);
        }
Exemplo n.º 26
0
        public void TestIListCorrectlyResolves()
        {
            using (var autosub = new AutoSubstitute())
            {
                var mockA     = autosub.Provide <IServiceItem, ServiceItemA>();
                var mockB     = autosub.Provide <IServiceItem, ServiceItemB>();
                var component = autosub.Resolve <TestIListComponent>();

                Assert.NotEmpty(component.ServiceItems);
                Assert.True(component.ServiceItems.Contains(mockA));
                Assert.True(component.ServiceItems.Contains(mockB));
            }
        }
Exemplo n.º 27
0
        public void ProvideMock()
        {
            using (var autoSubstitute = new AutoSubstitute())
            {
                var mockA = Substitute.For <IServiceA>();
                autoSubstitute.Provide(mockA);

                var component = autoSubstitute.Resolve <TestComponent>();
                component.RunAll();

                mockA.Received().RunA();
            }
        }
 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>();
 }
Exemplo n.º 29
0
        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));
        }
 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 Should_Deal_WithHandlers_That_Not_Also_Resolvers2()
        {
            // Given
            var handlerMatcher = AutoSubstitute.Resolve <ResolveCommandMatcher>();
            var resolveHandler = Substitute.For <ICompletionResolveHandler>();

            resolveHandler.CanResolve(Arg.Any <CompletionItem>()).Returns(true);
            var resolveHandler2 = Substitute.For(new Type[] {
                typeof(ICompletionHandler),
                typeof(ICompletionResolveHandler)
            }, new object[0]);

            (resolveHandler2 as ICompletionResolveHandler).CanResolve(Arg.Any <CompletionItem>()).Returns(false);

            // When
            var result = handlerMatcher.FindHandler(new CompletionItem()
            {
                Data = new JObject()
            },
                                                    new List <LspHandlerDescriptor> {
                new LspHandlerDescriptor(TextDocumentNames.CompletionResolve,
                                         "Key",
                                         resolveHandler,
                                         resolveHandler.GetType(),
                                         typeof(CompletionItem),
                                         null,
                                         null,
                                         () => false,
                                         null,
                                         null,
                                         () => { },
                                         Substitute.For <ILspHandlerTypeDescriptor>()),
                new LspHandlerDescriptor(TextDocumentNames.CompletionResolve,
                                         "Key2",
                                         resolveHandler2 as IJsonRpcHandler,
                                         typeof(ICompletionResolveHandler),
                                         typeof(CompletionItem),
                                         null,
                                         null,
                                         () => false,
                                         null,
                                         null,
                                         () => { },
                                         Substitute.For <ILspHandlerTypeDescriptor>()),
            })
                         .ToArray();

            // Then
            result.Should().NotBeNullOrEmpty();
            result.OfType <IHandlerDescriptor>().Should().Contain(x => x.Handler == resolveHandler);
        }
        public async Task ShouldRouteToCorrect_Request_WithManyHandlers_CodeLensHandler()
        {
            var textDocumentSyncHandler  = TextDocumentSyncHandlerExtensions.With(DocumentSelector.ForPattern("**/*.cs"), "csharp");
            var textDocumentSyncHandler2 = TextDocumentSyncHandlerExtensions.With(DocumentSelector.ForPattern("**/*.cake"), "csharp");

            textDocumentSyncHandler.Handle(Arg.Any <DidSaveTextDocumentParams>(), Arg.Any <CancellationToken>()).Returns(Unit.Value);
            textDocumentSyncHandler2.Handle(Arg.Any <DidSaveTextDocumentParams>(), Arg.Any <CancellationToken>()).Returns(Unit.Value);

            var codeActionHandler = Substitute.For <ICodeLensHandler>();

            codeActionHandler.GetRegistrationOptions().Returns(new CodeLensRegistrationOptions()
            {
                DocumentSelector = DocumentSelector.ForPattern("**/*.cs")
            });
            codeActionHandler
            .Handle(Arg.Any <CodeLensParams>(), Arg.Any <CancellationToken>())
            .Returns(new CodeLensContainer());

            var codeActionHandler2 = Substitute.For <ICodeLensHandler>();

            codeActionHandler2.GetRegistrationOptions().Returns(new CodeLensRegistrationOptions()
            {
                DocumentSelector = DocumentSelector.ForPattern("**/*.cake")
            });
            codeActionHandler2
            .Handle(Arg.Any <CodeLensParams>(), Arg.Any <CancellationToken>())
            .Returns(new CodeLensContainer());

            var collection = new HandlerCollection(SupportedCapabilitiesFixture.AlwaysTrue, new TextDocumentIdentifiers())
            {
                textDocumentSyncHandler, textDocumentSyncHandler2, codeActionHandler, codeActionHandler2
            };

            AutoSubstitute.Provide <IHandlerCollection>(collection);
            AutoSubstitute.Provide <IEnumerable <ILspHandlerDescriptor> >(collection);
            var mediator = AutoSubstitute.Resolve <LspRequestRouter>();

            var id      = Guid.NewGuid().ToString();
            var @params = new CodeLensParams()
            {
                TextDocument = new TextDocumentIdentifier(new Uri("file:///c:/test/123.cs"))
            };

            var request = new Request(id, DocumentNames.CodeLens, JObject.Parse(JsonConvert.SerializeObject(@params, new Serializer(ClientVersion.Lsp3).Settings)));

            await mediator.RouteRequest(mediator.GetDescriptor(request), request, CancellationToken.None);

            await codeActionHandler2.Received(0).Handle(Arg.Any <CodeLensParams>(), Arg.Any <CancellationToken>());

            await codeActionHandler.Received(1).Handle(Arg.Any <CodeLensParams>(), Arg.Any <CancellationToken>());
        }
        public async Task ShouldRouteToCorrect_Notification_WithManyHandlers()
        {
            var textDocumentSyncHandler =
                TextDocumentSyncHandlerExtensions.With(DocumentSelector.ForPattern("**/*.cs"), "csharp");
            var textDocumentSyncHandler2 =
                TextDocumentSyncHandlerExtensions.With(DocumentSelector.ForPattern("**/*.cake"), "csharp");

            textDocumentSyncHandler.Handle(Arg.Any <DidSaveTextDocumentParams>(), Arg.Any <CancellationToken>())
            .Returns(Unit.Value);
            textDocumentSyncHandler2.Handle(Arg.Any <DidSaveTextDocumentParams>(), Arg.Any <CancellationToken>())
            .Returns(Unit.Value);

            var textDocumentIdentifiers = new TextDocumentIdentifiers();

            AutoSubstitute.Provide(textDocumentIdentifiers);
            var collection =
                new SharedHandlerCollection(
                    SupportedCapabilitiesFixture.AlwaysTrue, textDocumentIdentifiers, Substitute.For <IResolverContext>(),
                    new LspHandlerTypeDescriptorProvider(
                        new[] {
                typeof(FoundationTests).Assembly, typeof(LanguageServer).Assembly, typeof(LanguageClient).Assembly, typeof(IRegistrationManager).Assembly,
                typeof(LspRequestRouter).Assembly
            }
                        )
                    )
            {
                textDocumentSyncHandler, textDocumentSyncHandler2
            };

            AutoSubstitute.Provide <IHandlerCollection>(collection);
            AutoSubstitute.Provide <IEnumerable <ILspHandlerDescriptor> >(collection);
            AutoSubstitute.Provide <IHandlerMatcher>(new TextDocumentMatcher(LoggerFactory.CreateLogger <TextDocumentMatcher>(), textDocumentIdentifiers));
            var mediator = AutoSubstitute.Resolve <LspRequestRouter>();

            var @params = new DidSaveTextDocumentParams {
                TextDocument = new TextDocumentIdentifier(new Uri("file:///c:/test/123.cake"))
            };

            var request = new Notification(
                TextDocumentNames.DidSave,
                JObject.Parse(JsonConvert.SerializeObject(@params, new Serializer(ClientVersion.Lsp3).Settings))
                );

            await mediator.RouteNotification(mediator.GetDescriptors(request), request, CancellationToken.None);

            await textDocumentSyncHandler.Received(0)
            .Handle(Arg.Any <DidSaveTextDocumentParams>(), Arg.Any <CancellationToken>());

            await textDocumentSyncHandler2.Received(1)
            .Handle(Arg.Any <DidSaveTextDocumentParams>(), Arg.Any <CancellationToken>());
        }
Exemplo n.º 34
0
        public async Task RequestsCancellation()
        {
            var textDocumentSyncHandler = TextDocumentSyncHandlerExtensions.With(DocumentSelector.ForPattern("**/*.cs"), "csharp");

            textDocumentSyncHandler.Handle(Arg.Any <DidSaveTextDocumentParams>(), Arg.Any <CancellationToken>()).Returns(Unit.Value);

            var codeActionHandler = Substitute.For <ICodeActionHandler>();

            codeActionHandler.GetRegistrationOptions().Returns(new CodeActionRegistrationOptions()
            {
                DocumentSelector = DocumentSelector.ForPattern("**/*.cs")
            });
            codeActionHandler
            .Handle(Arg.Any <CodeActionParams>(), Arg.Any <CancellationToken>())
            .Returns(async(c) =>
            {
                await Task.Delay(1000, c.Arg <CancellationToken>());
                throw new XunitException("Task was not cancelled in time!");
                return(new CommandOrCodeActionContainer());
            });

            var collection = new HandlerCollection(SupportedCapabilitiesFixture.AlwaysTrue, new TextDocumentIdentifiers())
            {
                textDocumentSyncHandler, codeActionHandler
            };

            AutoSubstitute.Provide <IHandlerCollection>(collection);
            AutoSubstitute.Provide <IEnumerable <ILspHandlerDescriptor> >(collection);
            var mediator = AutoSubstitute.Resolve <LspRequestRouter>();

            var id      = Guid.NewGuid().ToString();
            var @params = new CodeActionParams()
            {
                TextDocument = new TextDocumentIdentifier(new Uri("file:///c:/test/123.cs")),
                Range        = new Range(new Position(1, 1), new Position(2, 2)),
                Context      = new CodeActionContext()
                {
                    Diagnostics = new Container <Diagnostic>()
                }
            };

            var request = new Request(id, "textDocument/codeAction", JObject.Parse(JsonConvert.SerializeObject(@params, new Serializer(ClientVersion.Lsp3).Settings)));

            var response = ((IRequestRouter <ILspHandlerDescriptor>)mediator).RouteRequest(request, CancellationToken.None);

            mediator.CancelRequest(id);
            var result = await response;

            result.IsError.Should().BeTrue();
            result.Error.Should().BeEquivalentTo(new RequestCancelled());
        }
Exemplo n.º 35
0
        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));
        }
Exemplo n.º 36
0
        public async Task CreateTrail_ReturnsServiceError_WhenRepoCallFails()
        {
            var autoSub = new AutoSubstitute();

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

            trailsRepo.CreateTrail(Arg.Any <Trail>()).Throws(new Exception("Error creating trail"));

            var(result, error) = await autoSub.Resolve <TrailsService>().CreateTrail(new Trail());

            Assert.Equal(0, result);
            Assert.NotNull(error);
            Assert.Equal("Error creating trail", error.Exception.Message);
        }
        public static void ShouldAcceptProvidedIndexedDependency()
        {
            var substitute = Substitute.For <IDependency2>();

            using var autoSubstitute = AutoSubstitute.Configure()
                                       .Provide(substitute, Switch.On)
                                       .Build();

            substitute.SomeOtherMethod().Returns(5);

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

            Assert.That(target.OnDependency.SomeOtherMethod(), Is.EqualTo(5));
        }
Exemplo n.º 38
0
        public async Task GetTrail_ReturnsTrail_WhenSuccessful()
        {
            var autoSub = new AutoSubstitute();

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

            trailsRepo.GetTrail(Arg.Any <int>()).Returns(new Trail());

            var(result, error) = await autoSub.Resolve <TrailsService>().GetTrail(1);

            Assert.NotNull(result);
            Assert.Null(error);
            Assert.IsType <Trail>(result);
        }
Exemplo n.º 39
0
        public async Task CreateTrail_ReturnsShiny_WhenSuccessful()
        {
            var autoSub = new AutoSubstitute();

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

            trailsRepo.CreateTrail(Arg.Any <Trail>()).Returns(1);

            var(result, error) = await autoSub.Resolve <TrailsService>().CreateTrail(new Trail());

            Assert.Equal(1, result);
            Assert.Null(error);
            Assert.IsType <int>(result);
        }
Exemplo n.º 40
0
        public ImageManagementServiceTests(ITestOutputHelper testOutputHelper)
            : base(testOutputHelper)
        {
            _autoSubstitute = new AutoSubstitute();

            _testSchedulerProvider = new TestSchedulerProvider();
            _autoSubstitute.Provide <ISchedulerProvider>(_testSchedulerProvider);

            _unitOfWorkQueue = new Queue <IUnitOfWork>();
            _autoSubstitute.Provide <Func <IUnitOfWork> >(() => _unitOfWorkQueue.Dequeue());

            _mockFileSystem = new MockFileSystem();
            _autoSubstitute.Provide <IFileSystem>(_mockFileSystem);
        }
Exemplo n.º 41
0
        public void ProvidesPartsOfBuiltin()
        {
            using (var fake = new AutoSubstitute())
            {
                var bar = fake.ProvidePartsOf <IBar, Bar>();
                bar.When(x => x.Fuzz()).DoNotCallBase();
                bar.Fuzz().Returns("Fuzz");

                var foo    = fake.Resolve <Foo>();
                var result = foo.Fuzz();

                Assert.Equal("Fuzz", result);
            }
        }
Exemplo n.º 42
0
        public void Init()
        {
            AutoSubstitute = new AutoSubstitute();

            // Register commonlog module
            AutoSubstitute = new AutoSubstitute((builder) =>
            {
                //builder.RegisterModule<CommonLoggingModule>();
                //builder.RegisterGeneric(typeof(UnitOfWork<>)).As(typeof(IUnitOfWork<>));
                builder.RegisterType <FirstDbContext>().InstancePerLifetimeScope();
            });
            //AutoSubstitute.Resolve<IDBOneRepositories>();
            //AutoSubstitute.Resolve<ICategoryRepository>();
        }
Exemplo n.º 43
0
        public async Task GetTrails_ReturnsServiceError_WhenRepoCallFails()
        {
            var autoSub = new AutoSubstitute();

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

            trailsRepo.GetAllTrails().Throws(new Exception("Error retrieving trails"));

            var(result, error) = await autoSub.Resolve <TrailsService>().GetTrails();

            Assert.Null(result);
            Assert.NotNull(error);
            Assert.Equal("Error retrieving trails", error.Exception.Message);
        }
        public void ProvideMock()
        {
            var mockA = Substitute.For <IServiceA>();

            using var autoSubstitute = AutoSubstitute.Configure()
                                       .Provide(mockA)
                                       .Build();

            var component = autoSubstitute.Resolve <TestComponent>();

            component.RunAll();

            mockA.Received().RunA();
        }
        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;
        }
Exemplo n.º 46
0
        public void TooLarge(int level)
        {
            // Arrange
            using var container = AutoSubstitute.Configure()
                                  .InitializeHttpWrappers()
                                  .ConfigureParameters(a => a.Add("Q", $"{level},2,3"))
                                  .Build();

            // Act
            container.Resolve <DSSProvider>().Run(container.Resolve <IWwtContext>());

            // Assert
            container.Resolve <HttpResponseBase>().Received(1).Write("No image");
        }
Exemplo n.º 47
0
        public void Should_Return_Code_Lens_Descriptor()
        {
            // Given
            var textDocumentSyncHandler =
                TextDocumentSyncHandlerExtensions.With(DocumentSelector.ForPattern("**/*.cs"));
            var collection = new HandlerCollection(SupportedCapabilitiesFixture.AlwaysTrue)
            {
                textDocumentSyncHandler
            };

            AutoSubstitute.Provide <IHandlerCollection>(collection);
            AutoSubstitute.Provide <IEnumerable <ILspHandlerDescriptor> >(collection);
            var handlerMatcher = AutoSubstitute.Resolve <TextDocumentMatcher>();

            var codeLensHandler = Substitute.For(new Type[] { typeof(ICodeLensHandler), typeof(ICodeLensResolveHandler) }, new object[0]) as ICodeLensHandler;

            codeLensHandler.GetRegistrationOptions()
            .Returns(new CodeLensRegistrationOptions()
            {
                DocumentSelector = new DocumentSelector(new DocumentFilter {
                    Pattern = "**/*.cs"
                })
            });

            var codeLensHandler2 = Substitute.For(new Type[] { typeof(ICodeLensHandler), typeof(ICodeLensResolveHandler) }, new object[0]) as ICodeLensHandler;

            codeLensHandler2.GetRegistrationOptions()
            .Returns(new CodeLensRegistrationOptions()
            {
                DocumentSelector = new DocumentSelector(new DocumentFilter {
                    Pattern = "**/*.cake"
                })
            });
            collection.Add(codeLensHandler, codeLensHandler2);

            // When
            var result = handlerMatcher.FindHandler(new CodeLensParams()
            {
                TextDocument = new VersionedTextDocumentIdentifier {
                    Uri = new Uri("file:///abc/123/d.cs"), Version = 1
                }
            },
                                                    collection.Where(x => x.Method == DocumentNames.CodeLens));

            // Then
            result.Should().NotBeNullOrEmpty();
            result.Should().Contain(x => x.Method == DocumentNames.CodeLens);
            result.Should().Contain(x => ((HandlerDescriptor)x).Key == "[**/*.cs]");
        }
        public async Task ShouldRouteToCorrect_Request()
        {
            var textDocumentSyncHandler =
                TextDocumentSyncHandlerExtensions.With(DocumentSelector.ForPattern("**/*.cs"), "csharp");

            textDocumentSyncHandler.Handle(Arg.Any <DidSaveTextDocumentParams>(), Arg.Any <CancellationToken>())
            .Returns(Unit.Value);

            var codeActionHandler = Substitute.For <ICodeActionHandler>();

            codeActionHandler.GetRegistrationOptions().Returns(new CodeActionRegistrationOptions {
                DocumentSelector = DocumentSelector.ForPattern("**/*.cs")
            });
            codeActionHandler
            .Handle(Arg.Any <CodeActionParams>(), Arg.Any <CancellationToken>())
            .Returns(new CommandOrCodeActionContainer());

            var collection =
                new SharedHandlerCollection(
                    SupportedCapabilitiesFixture.AlwaysTrue, new TextDocumentIdentifiers(), Substitute.For <IResolverContext>(),
                    new LspHandlerTypeDescriptorProvider(
                        new[] {
                typeof(FoundationTests).Assembly, typeof(LanguageServer).Assembly, typeof(LanguageClient).Assembly, typeof(IRegistrationManager).Assembly,
                typeof(LspRequestRouter).Assembly
            }
                        )
                    )
            {
                textDocumentSyncHandler, codeActionHandler
            };

            AutoSubstitute.Provide <IHandlerCollection>(collection);
            AutoSubstitute.Provide <IEnumerable <ILspHandlerDescriptor> >(collection);
            var mediator = AutoSubstitute.Resolve <LspRequestRouter>();

            var id      = Guid.NewGuid().ToString();
            var @params = new DidSaveTextDocumentParams {
                TextDocument = new TextDocumentIdentifier(new Uri("file:///c:/test/123.cs"))
            };

            var request = new Request(
                id, TextDocumentNames.CodeAction,
                JObject.Parse(JsonConvert.SerializeObject(@params, new Serializer(ClientVersion.Lsp3).Settings))
                );

            await mediator.RouteRequest(mediator.GetDescriptors(request), request, CancellationToken.None);

            await codeActionHandler.Received(1).Handle(Arg.Any <CodeActionParams>(), Arg.Any <CancellationToken>());
        }
        public void Should_Return_CodeLensResolve_Descriptor()
        {
            // Given
            var handlerMatcher  = AutoSubstitute.Resolve <ResolveCommandMatcher>();
            var resolveHandler  = (ICodeLensResolveHandler)Substitute.For(new[] { typeof(ICodeLensResolveHandler), typeof(ICanBeIdentifiedHandler) }, Array.Empty <object>());
            var resolveHandler2 = (ICodeLensResolveHandler)Substitute.For(new[] { typeof(ICodeLensResolveHandler), typeof(ICanBeIdentifiedHandler) }, Array.Empty <object>());

            resolveHandler.Id.Returns(_falseId);
            resolveHandler2.Id.Returns(_trueId);

            // When
            var result = handlerMatcher.FindHandler(
                new CodeLens {
                Data = JObject.FromObject(new Dictionary <string, object> {
                    [Constants.PrivateHandlerId] = _trueId, ["a"] = 1
                })
            },
                new List <LspHandlerDescriptor> {
                new LspHandlerDescriptor(
                    0,
                    TextDocumentNames.CodeLensResolve,
                    "Key",
                    resolveHandler !,
                    resolveHandler.GetType(),
                    typeof(CodeLens),
                    null,
                    null,
                    null,
                    null,
                    null,
                    () => { },
                    Substitute.For <ILspHandlerTypeDescriptor>()
                    ),
                new LspHandlerDescriptor(
                    0,
                    TextDocumentNames.CodeLensResolve,
                    "Key2",
                    resolveHandler2,
                    typeof(ICodeLensResolveHandler),
                    typeof(CodeLens),
                    null,
                    null,
                    null,
                    null,
                    null,
                    () => { },
                    Substitute.For <ILspHandlerTypeDescriptor>()
                    ),
            }
        public void DisableMockGenerationOnProvide()
        {
            var mock = AutoSubstitute.Configure()
                       .ConfigureOptions(options =>
            {
                options.AutomaticallySkipMocksForProvidedValues = true;
            })
                       .Provide <IDependency, Impl1>(out var impl1)
                       .Provide <IDependency, Impl2>(out var impl2)
                       .Build();

            var items = mock.Resolve <IEnumerable <IDependency> >();

            CollectionAssert.AreEqual(items, new[] { impl1.Value, impl2.Value });
        }
        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 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 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_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));
        }
Exemplo n.º 56
0
 public void TestInitialize()
 {
     _autoSubstitute = new AutoSubstitute();
     _eventHandlers = new List<IEventHandler<FakeEvent>>();
 }
        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));
        }
 public void SetUp()
 {
     _autoSubstitute = AutoSubstituteContainer.Create();
     _controller = _autoSubstitute.GetController<PageController>();
 }
        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 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));
        }