public void SetUp() { Moqer = new AutoMoqer(); _account = new Account(1, 12000, 300, 0, 0); Moqer.SetInstance(_account); _commitment = new CommitmentModel { EmployerAccountId = 1, ApprenticeshipId = 2, LearnerId = 3, StartDate = DateTime.Today.AddMonths(-1), PlannedEndDate = DateTime.Today.AddMonths(25), MonthlyInstallment = 2100, NumberOfInstallments = 24, CompletionAmount = 3000, FundingSource = Models.Payments.FundingSource.Levy }; _commitments = new EmployerCommitmentsModel { LevyFundedCommitments = new List <CommitmentModel> { _commitment } }; var employerCommitments = new EmployerCommitments(1, _commitments); Moqer.SetInstance(employerCommitments); }
public void Setup() { mocker = new AutoMoqer(); mocker.SetInstance <IIndentValidator>(validator); mocker.SetInstance <IRainbowBrushGetter>(rainbowgetter); decorator = mocker.Resolve <MonocolorLineDecorator>(); }
public void Can_register_and_resolve_a_list_using_the_declared_type() { var dependency = new Dependency(); IList <Dependency> list = new List <Dependency>(); list.Add(dependency); mocker.SetInstance(list); var thing = mocker.Create <ThingThatHasDependencies>(); Assert.Same(thing.FindOne(), dependency); }
public void CanRegisterAndResolveAListUsingTheDeclaredType() { var dependency = new Dependency(); IList <Dependency> list = new List <Dependency>(); list.Add(dependency); mocker.SetInstance(list); var thing = mocker.Create <ThingThatHasDependencies>(); thing.FindOne().Should().BeSameAs(dependency); }
public void Setup() { testContainer = new UnityContainer(); autoMocker = new AutoMoqer(this.testContainer); createProjectViewModelMock = new Mock<ICreateProjectViewModel>(); navigationServiceMock = new Mock<INavigationService>(); navigationServiceMock.SetupAllProperties(); userServiceMock = new Mock<IUserService>(); viewModelFactoryMock = new Mock<IViewModelFactory>(); autoMocker.SetInstance(createProjectViewModelMock.Object); autoMocker.SetInstance(navigationServiceMock.Object); autoMocker.SetInstance(userServiceMock.Object); autoMocker.SetInstance(viewModelFactoryMock.Object); }
public void SetUp() { _moqer = new AutoMoqer(); _previousAccountBalance = new BalanceModel { EmployerAccountId = 12345, BalancePeriod = DateTime.MinValue, }; _currentAccountBalance = new BalanceModel { EmployerAccountId = 12345, BalancePeriod = DateTime.Today, Amount = 10000, TransferAllowance = 1000, RemainingTransferBalance = 1000 }; _moqer.SetInstance(new EmployerCommitments(12345, new EmployerCommitmentsModel { LevyFundedCommitments = new List <CommitmentModel> { new CommitmentModel { EmployerAccountId = 12345, PlannedEndDate = DateTime.Today.AddMonths(-2), StartDate = DateTime.Today.AddMonths(-3), NumberOfInstallments = 1, CompletionAmount = 1000, MonthlyInstallment = 80, HasHadPayment = true, FundingSource = FundingSource.Levy }, new CommitmentModel { EmployerAccountId = 12345, PlannedEndDate = DateTime.Today.AddMonths(-1), StartDate = DateTime.Today.AddMonths(-3), NumberOfInstallments = 1, CompletionAmount = 1000, MonthlyInstallment = 80, HasHadPayment = true, FundingSource = FundingSource.Levy } } })); _moqer.SetInstance(_previousAccountBalance); _moqer.GetMock <IAccountBalanceService>() .Setup(svc => svc.GetAccountBalance(It.IsAny <long>())) .Returns(Task.FromResult <BalanceModel>(_currentAccountBalance)); }
public void WhenAuthorizationCodeHasExpired_ThenThrowException() { var mocker = new AutoMoqer(); mocker.GetMock <IOAuthRequest>().Setup(x => x.GrantType).Returns(GrantType.AuthorizationCode); mocker.GetMock <IConfiguration>().Setup(x => x.AuthorizationTokenExpirationLength).Returns(300); mocker.SetInstance <IOAuthIssuer>(new OAuthIssuer()); var issuer = new OAuthIssuer(); var token = issuer.GenerateAuthorizationToken(new TokenData { ConsumerId = 1, Timestamp = DateTime.UtcNow.AddHours(-1).Ticks }); mocker.GetMock <IOAuthRequest>().Setup(x => x.AuthorizationCode).Returns(token); var authorizer = mocker.Resolve <AuthorizationCodeAuthorizer>(); try { authorizer.Authorize(mocker.GetMock <IOAuthRequest>().Object); Assert.Fail("Exception not thrown"); } catch (OAuthException ex) { Assert.AreEqual(ErrorCode.InvalidRequest, ex.ErrorCode); Assert.IsTrue(ex.ErrorDescription.HasValue()); } }
public void WhenConsumerIsNolongerApproved_ThenThrowsException() { var mocker = new AutoMoqer(); mocker.GetMock <IOAuthRequest>().Setup(x => x.ContentType).Returns(ContentType.FormEncoded); mocker.GetMock <IOAuthRequest>().Setup(x => x.ClientId).Returns("clientid"); mocker.GetMock <IOAuthRequest>().Setup(x => x.GrantType).Returns(GrantType.RefreshToken); mocker.GetMock <IConsumerRepository>().Setup(x => x.GetByClientId("clientid")).Returns(new ConsumerImpl { ConsumerId = 12, ClientId = "clientid", Secret = "clientsecret" }); mocker.GetMock <IResourceOwnerRepository>().Setup(x => x.IsConsumerApproved(10, 12)).Returns(false); mocker.GetMock <IOAuthRequest>().Setup(x => x.ClientSecret).Returns("clientsecret"); mocker.SetInstance <IOAuthIssuer>(new OAuthIssuer()); var issuer = new OAuthIssuer(); var authorizer = mocker.Resolve <RefreshTokenRequestAuthorizer>(); var token = issuer.GenerateRefreshToken(new TokenData { ConsumerId = 12, ResourceOwnerId = 10, Timestamp = 1 }); mocker.GetMock <IOAuthRequest>().Setup(x => x.RefreshToken).Returns(token); try { authorizer.Authorize(mocker.GetMock <IOAuthRequest>().Object); Assert.Fail("Exception not thrown"); } catch (OAuthException ex) { Assert.AreEqual(ErrorCode.UnauthorizedClient, ex.ErrorCode); Assert.IsTrue(!string.IsNullOrWhiteSpace(ex.ErrorDescription)); } }
public void Setup() { _mocker = new AutoMoqer(); var mockFileSystem = new MockFileSystem(); _mocker.SetInstance<IFileSystem>(mockFileSystem); // GetMock of the abstract class before create to prevent automoq bugs _mocker.GetMock<FileSystemWatcherBase>(); _instance = _mocker.Create<DirectoryWatcher>(); // Mocked files var content = new byte[] {1, 1, 1}; _expectedFileLength = content.Length; _expectedWriteDate = DateTime.Now.ToUniversalTime(); var nameWithPath = mockFileSystem.Path.Combine(Path, FileName); mockFileSystem.AddFile(nameWithPath, new MockFileData(content) { LastWriteTime = _expectedWriteDate }); _trackedFile = new TrackedFile(); _mocker.GetMock<ITrackedFileStore>() .Setup(x => x.GetTrackedFileByFullPath(nameWithPath)) .Returns(_trackedFile); }
public void Setup() { _autoMoqer = new AutoMoqer(); _memoryDatabaseProvider = new MemoryDatabaseProvider(); _memoryDatabaseProvider.SetKeyColumn("Users", "Id"); _autoMoqer.SetInstance <IDatabaseProvider>(_memoryDatabaseProvider); }
public void UsesRegistryToGetNewComics() { var mocker = new AutoMoqer(); var lastExplosmComic = new Comic(); var newExplosmComic1 = new Comic(); var newExplosmComic2 = new Comic(); var explosm = new Mock<IComicDownloader>(); explosm.Setup(m => m.GetNewComicsSince(lastExplosmComic)) .Returns(new[] { newExplosmComic1, newExplosmComic2 }); mocker.GetMock<IComicsRepository>() .Setup(m => m.GetLastImportedComic(ComicType.Explosm)) .Returns(lastExplosmComic) .Verifiable(); var registry = new ComicConfigRegistry(); registry.Add(new ComicConfig(ComicType.Explosm, explosm.Object)); // ReSharper disable once RedundantTypeArgumentsOfMethod mocker.SetInstance<ComicConfigRegistry>(registry); mocker.Create<ImportProcess>() .Run(); mocker.GetMock<IComicsRepository>().VerifyAll(); mocker.GetMock<IComicsRepository>() .Verify(m => m.InsertComic(newExplosmComic1), Times.Once); mocker.GetMock<IComicsRepository>() .Verify(m => m.InsertComic(newExplosmComic2), Times.Once); }
public void Setup() { _autoMoqer = new AutoMoqer(); _memoryDatabaseProvider = new MemoryDatabaseProvider(); _memoryDatabaseProvider.SetKeyColumn("Users", "Id"); _autoMoqer.SetInstance<IDatabaseProvider>(_memoryDatabaseProvider); }
public void EnsureApplicationIsApproved() { var mocker = new AutoMoqer(); mocker.MockServiceLocator(); mocker.GetMock <IOAuthRequest>().Setup(x => x.ContentType).Returns(ContentType.FormEncoded); mocker.GetMock <IOAuthRequest>().Setup(x => x.ClientId).Returns("clientid"); mocker.GetMock <IOAuthRequest>().Setup(x => x.ClientSecret).Returns("clientsecret"); mocker.GetMock <IOAuthRequest>().Setup(x => x.Username).Returns("username"); mocker.GetMock <IOAuthRequest>().Setup(x => x.GrantType).Returns(GrantType.Password); mocker.GetMock <IConsumerRepository>().Setup(x => x.GetByClientId("clientid")).Returns(new ConsumerImpl { ConsumerId = 1, ClientId = "clientid", Secret = "clientsecret" }); mocker.GetMock <IResourceOwnerRepository>().Setup(x => x.GetByUsername(1, "username")).Returns(new ResourceOwnerImpl { ResourceOwnerId = 2, Username = "******", Password = "******".ToHash() }); mocker.GetMock <IPasswordHasher>().Setup(x => x.CheckPassword("password", "password".ToHash())).Returns(true); mocker.GetMock <IOAuthRequest>().Setup(x => x.Password).Returns("password"); mocker.SetInstance <IOAuthIssuer>(new OAuthIssuer()); var authorizer = mocker.Resolve <PasswordTokenRequestAuthorizer>(); var token = authorizer.Authorize(mocker.GetMock <IOAuthRequest>().Object); mocker.GetMock <IResourceOwnerRepository>().Verify(x => x.ApproveConsumer(2, 1), Times.Once()); }
public void ReportsComicsImported() { var mocker = new AutoMoqer(); var lastExplosmComic = new Comic(); var newExplosmComic1 = new Comic(); var newExplosmComic2 = new Comic(); var explosm = new Mock<IComicDownloader>(); explosm.Setup(m => m.GetNewComicsSince(lastExplosmComic)) .Returns(new[] { newExplosmComic1, newExplosmComic2 }); mocker.GetMock<IComicsRepository>() .Setup(m => m.GetLastImportedComic(ComicType.Explosm)) .Returns(lastExplosmComic) .Verifiable(); var registry = new ComicConfigRegistry(); registry.Add(new ComicConfig(ComicType.Explosm, explosm.Object)); // ReSharper disable once RedundantTypeArgumentsOfMethod mocker.SetInstance<ComicConfigRegistry>(registry); var process = mocker.Create<ImportProcess>(); process.Run(); Check.That(process.ImportedComics.Count).IsEqualTo(2); }
public void BaseSetup() { _subject = null; Mocker = new AutoMoqer(); Mocker.SetInstance(logger); LogConfigurator.EnableConsoleTarget(LogConfigurator.DetailedLayout, LogLevel.Trace); }
public void First_Month_Is_Current_Month() { //Arrange _moqer.SetInstance <IDateTimeService>(new DateTimeService()); _estimationProjection = new AccountEstimationProjection( _moqer.Resolve <Account>(), _moqer.Resolve <AccountEstimationProjectionCommitments>(), _moqer.Resolve <IDateTimeService>(), false); //Act _estimationProjection.BuildProjections(); var projection = _estimationProjection.Projections.FirstOrDefault(); //Assert Assert.IsNotNull(projection); Assert.IsTrue(projection.Month == DateTime.Now.Month && projection.Year == DateTime.Now.Year); }
public RecipeBookRequestHandlerTests() { autoMoqer = new AutoMoqer(); cancellationToken = new CancellationToken(); var mapper = new MapperConfiguration(c => c.AddProfile <RecipeBookObjectMapper>()).CreateMapper(); autoMoqer.SetInstance(mapper); recipeBookRequestHandler = autoMoqer.Create <RecipeBookRequestHandler>(); }
public HomeControllerTests() { _mocker = new AutoMoqer(); _registry = new ComicConfigRegistry(); _mocker.SetInstance(_registry); _latestDilbert = RegisterComic(ComicType.Dilbert); _latestExplosm = RegisterComic(ComicType.Explosm); }
public void can_create_parent_object_when_setInstance_is_called_on_child() { var autoMoq = new AutoMoqer(); // the second line works... seems to be an issue calling Create twice? var child = autoMoq.Create<Child>(); //var child = new Mock<IChild>().Object; autoMoq.SetInstance<IChild>(child); var parent = autoMoq.Create<Parent>(); Assert.IsNotNull(parent); }
public void CanCreateRegisteredInstance() { // arrange var target = new AutoMoqer(); var expected = new DummyCustomerRepository(); target.SetInstance <ICustomerRepository>(expected); // act var result = target.Create <ICustomerRepository>(); // assert Assert.Same(expected, result); }
public void can_create_parent_object_when_setInstance_is_called_on_child() { var autoMoq = new AutoMoqer(); // the second line works... seems to be an issue calling Create twice? var child = autoMoq.Create <Child>(); //var child = new Mock<IChild>().Object; autoMoq.SetInstance <IChild>(child); var parent = autoMoq.Create <Parent>(); Assert.IsNotNull(parent); }
public void DeveTrocarImplementacaoDaDependenciaDaClasseConcreta() { var mocker = new AutoMoqer(); var customWheelRepository = mocker.Create <CustomWheelRepository>(); mocker.SetInstance <IWheelRepository>(customWheelRepository); var carRepository = mocker.Create <CarRepository>(); var carro = carRepository.Criar(); carro.ShouldBeEquivalentTo(new { Personalizada = true }); }
public void CreatedInstanceHasRegisteredDependency() { // arrange var target = new AutoMoqer(); var expected = new DummyCustomerRepository(); // act target.SetInstance <ICustomerRepository>(expected); var result = target.Create <CustomerRepositoryContainer>() .CustomerRepository; // assert Assert.Equal(expected, result); }
public SignInUserCommandShould() { fixture = TestFixture.Create(); mocker = new AutoMoqer(); user = new PlannerAppUser { Email = EMAIL, TenantID = TENANTID }; mocker.SetInstance <IConfiguration>(new ConfigurationMock()); mocker.GetMock <IUserService>() .Setup(u => u.SignIn(It.IsAny <string>(), It.IsAny <string>())) .ReturnsAsync(user); sut = mocker.Create <SignInUserCommand>(); }
public void SelectConstructorWithNonAbstractParameterIfItIsRegistered() { // arrange var target = new AutoMoqer(); var expected = "It works"; target.SetInstance(expected); // act var result = target.Create <CustomerRepositoryContainer>() .Name; // assert Assert.Equal(expected, result); }
public void Registering_instance_for_Interface_injects_that_Instance() { //Arrange var mocker = new AutoMoqer(); var instance = new Dependency(); mocker.SetInstance <IDependency>(instance); //Act var result = mocker.Create <ClassWithDependencies>().Dependency; //Assert Assert.AreEqual(instance, result); }
private void SetUpProviders(bool provider1First, string provider1Provides, string provider2Provides) { callOrder = new List <int>(); var mockOrderMetadata1 = new Mock <IOrderMetadata>(); mockOrderMetadata1.Setup(o => o.Order).Returns(provider1First ? 1 : 2); var mockOrderMetadata2 = new Mock <IOrderMetadata>(); mockOrderMetadata2.Setup(o => o.Order).Returns(provider1First ? 2 : 1); var mockCoverageToolOutputFolderProvider1 = new Mock <ICoverageToolOutputFolderSolutionProvider>(); mockCoverageToolOutputFolderProvider1.Setup(p => p.Provide(It.IsAny <Func <string> >())).Returns(provider1Provides).Callback(() => callOrder.Add(1)); var mockCoverageToolOutputFolderProvider2 = new Mock <ICoverageToolOutputFolderSolutionProvider>(); mockCoverageToolOutputFolderProvider2.Setup(p => p.Provide(It.IsAny <Func <string> >())).Returns(provider2Provides).Callback(() => callOrder.Add(2)); List <Lazy <ICoverageToolOutputFolderSolutionProvider, IOrderMetadata> > lazyOrderedProviders = new List <Lazy <ICoverageToolOutputFolderSolutionProvider, IOrderMetadata> > { new Lazy <ICoverageToolOutputFolderSolutionProvider, IOrderMetadata>(() => mockCoverageToolOutputFolderProvider1.Object, mockOrderMetadata1.Object), new Lazy <ICoverageToolOutputFolderSolutionProvider, IOrderMetadata>(() => mockCoverageToolOutputFolderProvider2.Object, mockOrderMetadata2.Object) }; mocker.SetInstance <IEnumerable <Lazy <ICoverageToolOutputFolderSolutionProvider, IOrderMetadata> > >(lazyOrderedProviders); }
public void Setup() { _autoMoq = new AutoMoqer(); var _model = new AccountEstimationModel { Id = Guid.NewGuid().ToString("N"), Apprenticeships = new List <VirtualApprenticeship>(), EmployerAccountId = AccountId, EstimationName = "default" }; var p = _autoMoq.GetMock <IAccountEstimationProjection>(); p.Setup(x => x.BuildProjections()).Verifiable(); IList <AccountProjectionReadModel> projectionModel = new List <AccountProjectionReadModel> { new AccountProjectionReadModel { EmployerAccountId = 10000, Month = 4, Year = 2018, FutureFunds = 15000m, TotalCostOfTraining = 0m } }; p.Setup(o => o.Projections) .Returns(new ReadOnlyCollection <AccountProjectionReadModel>(projectionModel)); _autoMoq.SetInstance(_model); _autoMoq.GetMock <IHashingService>() .Setup(o => o.DecodeValue(HashedAccountId)) .Returns(AccountId); _autoMoq.GetMock <IAccountEstimationRepository>() .Setup(x => x.Get(It.IsAny <long>())) .Returns(Task.FromResult(_autoMoq.Resolve <AccountEstimation>())); _autoMoq.GetMock <IAccountEstimationProjectionRepository>() .Setup(x => x.Get(It.IsAny <AccountEstimation>())) .Returns(Task.FromResult(p.Object)); _estimationOrchestrator = _autoMoq.Resolve <EstimationOrchestrator>(); }
public void SetUp() { _moqer = new AutoMoqer(); _moqer.GetMock <IPayrollDateService>() .Setup(svc => svc.GetPayrollDate(It.IsAny <string>(), It.IsAny <short>())) .Returns(DateTime.Today); _model = new LevyDeclarationModel { EmployerAccountId = 12345, Id = 99, Scheme = "ABC/123", PayrollMonth = 1, PayrollYear = "18-19", }; _moqer.SetInstance(_model); }
public BookServiceContext() { var config = new MapperConfiguration(cfg => { cfg.AddProfile <DtoToDomainConfiguration>(); cfg.AddProfile <DomainToDtoConfiguration>(); }); Mapper = config.CreateMapper(); mocker = new AutoMoqer(); mocker.SetInstance(Mapper); BookRepository = mocker.GetMock <IBookRepository>(); Validator = mocker.GetMock <IBaseValidator <BookDto> >(); UnitOfWork = mocker.GetMock <IUnitOfWork>(); }
public void Create_with_constant_concerete_dependency_uses_constant() { //Arrange var mocker = new AutoMoqer(); var constant = new VirtualDependency() { PropValue = Guid.NewGuid().ToString() }; mocker.SetInstance(constant); //Act var result = mocker.Create <ClassWithVirtualDependencies>().GetVirtualProperty(); //Assert Assert.AreEqual((object)constant.PropValue, result); }
public void EnsureApplicationIsApproved() { var mocker = new AutoMoqer(); mocker.GetMock<IOAuthRequest>().Setup(x => x.ContentType).Returns(ContentType.FormEncoded); mocker.GetMock<IOAuthRequest>().Setup(x => x.ClientId).Returns("clientid"); mocker.GetMock<IOAuthRequest>().Setup(x => x.ClientSecret).Returns("clientsecret"); mocker.GetMock<IOAuthRequest>().Setup(x => x.Username).Returns("username"); mocker.GetMock<IOAuthRequest>().Setup(x => x.GrantType).Returns(GrantType.Password); mocker.GetMock<IConsumerRepository>().Setup(x => x.GetByClientId("clientid")).Returns(new ConsumerImpl { ConsumerId = 1, ClientId = "clientid", Secret = "clientsecret" }); mocker.GetMock<IResourceOwnerRepository>().Setup(x => x.GetByUsername(1, "username")).Returns(new ResourceOwnerImpl { ResourceOwnerId = 2, Username = "******", Password = "******".ToHash() }); mocker.GetMock<IOAuthRequest>().Setup(x => x.Password).Returns("password"); mocker.SetInstance<IOAuthIssuer>(new OAuthIssuer()); var authorizer = mocker.Resolve<PasswordTokenRequestAuthorizer>(); var token = authorizer.Authorize(mocker.GetMock<IOAuthRequest>().Object); mocker.GetMock<IResourceOwnerRepository>().Verify(x => x.ApproveConsumer(2, 1), Times.Once()); }
public void Test2() { //Arrang3 var autoMoq = new AutoMoqer(); var cultureInfo = new CultureInfo("en-GB"); autoMoq.SetInstance(cultureInfo); //Act var aboutViewModel = autoMoq.Create <AboutViewModel>(); aboutViewModel.TestMeFalseCommand.Execute(null); //Assert //aboutViewModel.Title.CompareTo("About"); //Assert.Equal(aboutViewModel.Title,"About"); aboutViewModel.TestMeString.Should().Be("Try this"); // aboutViewModel.OpenWebCommand.Execute(null); }
public void WhenDataIsValid_ThenNewTokenIsCreated() { var mocker = new AutoMoqer(); mocker.GetMock <IOAuthRequest>().Setup(x => x.ContentType).Returns(ContentType.FormEncoded); mocker.GetMock <IOAuthRequest>().Setup(x => x.ClientId).Returns("clientid"); mocker.GetMock <IOAuthRequest>().Setup(x => x.GrantType).Returns(GrantType.RefreshToken); mocker.GetMock <IConsumerRepository>().Setup(x => x.GetByClientId("clientid")).Returns(new ConsumerImpl { ConsumerId = 12, ClientId = "clientid", Secret = "clientsecret" }); mocker.GetMock <IResourceOwnerRepository>().Setup(x => x.IsConsumerApproved(10, 12)).Returns(true); mocker.GetMock <IOAuthRequest>().Setup(x => x.ClientSecret).Returns("clientsecret"); mocker.SetInstance <IOAuthIssuer>(new OAuthIssuer()); var issuer = new OAuthIssuer(); var authorizer = mocker.Resolve <RefreshTokenRequestAuthorizer>(); var token = issuer.GenerateRefreshToken(new TokenData { ConsumerId = 12, ResourceOwnerId = 10, Timestamp = 1 }); mocker.GetMock <IOAuthRequest>().Setup(x => x.RefreshToken).Returns(token); var newToken = authorizer.Authorize(mocker.GetMock <IOAuthRequest>().Object); Assert.IsNotNull(newToken); var accessTokenData = issuer.DecodeAccessToken(newToken.AccessToken); Assert.IsNotNull(accessTokenData); Assert.AreEqual(10, accessTokenData.ResourceOwnerId); Assert.IsTrue(accessTokenData.Timestamp > DateTimeOffset.UtcNow.AddMinutes(-5).Ticks); var refreshTokenData = issuer.DecodeRefreshToken(newToken.RefreshToken); Assert.IsNotNull(refreshTokenData); Assert.AreEqual(12, refreshTokenData.ConsumerId); Assert.AreEqual(10, refreshTokenData.ResourceOwnerId); Assert.IsTrue(refreshTokenData.Timestamp > DateTimeOffset.UtcNow.AddMinutes(-5).Ticks); }
public FinancialApplicationTests() { var mocker = new AutoMoqer(); mocker.Create <FinancialAppService>(); mocker.Create <FinancialService>(); _financialService = mocker.Resolve <FinancialService>(); mocker.SetInstance <FinancialService>(_financialService); _financialAppService = mocker.Resolve <FinancialAppService>(); _financialAppServiceMock = mocker.GetMock <IFinancialAppService>(); _financialServiceMock = mocker.GetMock <IFinancialService>(); _financialServiceMock.Setup(c => c.CalculaJuros((double)100, (int)5)); //.ReturnsAsync(new JuroComposto { Valor = 0}); }
public void WhenRedirectUriDoesNotMatch_ThenExceptionIsThrown() { var mocker = new AutoMoqer(); mocker.GetMock <IOAuthRequest>().Setup(x => x.GrantType).Returns(GrantType.AuthorizationCode); mocker.GetMock <IConfiguration>().Setup(x => x.AuthorizationTokenExpirationLength).Returns(300); mocker.GetMock <IConfiguration>().Setup(x => x.AccessTokenExpirationLength).Returns(500); var issuer = new OAuthIssuer(); mocker.SetInstance <IOAuthIssuer>(issuer); var token = issuer.GenerateAuthorizationToken(new TokenData { ConsumerId = 1, Timestamp = DateTime.UtcNow.Ticks, RedirectUri = "http://test.com" }); mocker.GetMock <IOAuthRequest>().Setup(x => x.AuthorizationCode).Returns(token); var authorizer = mocker.Resolve <AuthorizationCodeAuthorizer>(); try { authorizer.Authorize(mocker.GetMock <IOAuthRequest>().Object); Assert.Fail("Exception not thrown"); } catch (OAuthException ex) { Assert.AreEqual(ErrorCode.InvalidRequest, ex.ErrorCode); Assert.IsTrue(ex.ErrorDescription.HasValue()); } mocker.GetMock <IOAuthRequest>().Setup(x => x.RedirectUri).Returns("http://test.com"); var result = authorizer.Authorize(mocker.GetMock <IOAuthRequest>().Object); Assert.IsNotNull(result); Assert.IsTrue(result.AccessToken.HasValue()); Assert.AreEqual(500, result.ExpiresIn); Assert.IsTrue(result.RefreshToken.HasValue()); }
public void SetUp() { _moqer = new AutoMoqer(); _moqer.SetInstance(new Models.Balance.BalanceModel { EmployerAccountId = 12345, ReceivedDate = DateTime.Today.AddMonths(-1), BalancePeriod = DateTime.Today.AddMonths(-1), }); var mockBalance = _moqer.GetMock <CurrentBalance>(); mockBalance.Setup(x => x.EmployerAccountId).Returns(12345); mockBalance.Setup(x => x.Amount).Returns(10000); mockBalance.Setup(x => x.RefreshBalance(It.IsAny <bool>(), It.IsAny <bool>())) .Returns(Task.FromResult <bool>(true)); var repo = _moqer.GetMock <ICurrentBalanceRepository>(); repo.Setup(x => x.Get(It.IsAny <long>())) .Returns(Task.FromResult(mockBalance.Object)); repo.Setup(x => x.Store(It.IsAny <CurrentBalance>())).Returns(Task.CompletedTask); }
public void ReturnsAccessToken() { var mocker = new AutoMoqer(); mocker.GetMock <IOAuthRequest>().Setup(x => x.GrantType).Returns(GrantType.AuthorizationCode); mocker.GetMock <IConfiguration>().Setup(x => x.AuthorizationTokenExpirationLength).Returns(300); mocker.GetMock <IConfiguration>().Setup(x => x.AccessTokenExpirationLength).Returns(500); var issuer = new OAuthIssuer(); mocker.SetInstance <IOAuthIssuer>(issuer); var token = issuer.GenerateAuthorizationToken(new TokenData { ConsumerId = 1, Timestamp = DateTime.UtcNow.Ticks }); mocker.GetMock <IOAuthRequest>().Setup(x => x.AuthorizationCode).Returns(token); var authorizer = mocker.Resolve <AuthorizationCodeAuthorizer>(); var result = authorizer.Authorize(mocker.GetMock <IOAuthRequest>().Object); Assert.IsNotNull(result); Assert.IsTrue(result.AccessToken.HasValue()); Assert.AreEqual(500, result.ExpiresIn); Assert.IsTrue(result.RefreshToken.HasValue()); }
public void ReturnsAuthorizedToken() { var mocker = new AutoMoqer(); mocker.GetMock<IOAuthRequest>().Setup(x => x.ContentType).Returns(ContentType.FormEncoded); mocker.GetMock<IOAuthRequest>().Setup(x => x.ClientId).Returns("clientid"); mocker.GetMock<IOAuthRequest>().Setup(x => x.ClientSecret).Returns("clientsecret"); mocker.GetMock<IOAuthRequest>().Setup(x => x.Username).Returns("username"); mocker.GetMock<IOAuthRequest>().Setup(x => x.GrantType).Returns(GrantType.Password); mocker.GetMock<IConsumerRepository>().Setup(x => x.GetByClientId("clientid")).Returns(new ConsumerImpl { ConsumerId = 1, ClientId = "clientid", Secret = "clientsecret" }); mocker.GetMock<IResourceOwnerRepository>().Setup(x => x.GetByUsername(1, "username")).Returns(new ResourceOwnerImpl { ResourceOwnerId = 2, Username = "******", Password = "******".ToHash() }); mocker.GetMock<IOAuthRequest>().Setup(x => x.Password).Returns("password"); mocker.GetMock<IConfiguration>().Setup(x => x.AccessTokenExpirationLength).Returns(3600); mocker.SetInstance<IOAuthIssuer>(new OAuthIssuer()); var authorizer = mocker.Resolve<PasswordTokenRequestAuthorizer>(); var token = authorizer.Authorize(mocker.GetMock<IOAuthRequest>().Object); mocker.GetMock<IResourceOwnerRepository>().Verify(x => x.ApproveConsumer(2, 1), Times.Once()); Assert.IsNotNull(token); Assert.IsNotNull(token.AccessToken); Assert.AreEqual(3600, token.ExpiresIn); Assert.IsNotNull(token.RefreshToken); }
public void Setup() { _mocker = new AutoMoqer(); // GetMock of the abstract class before create to prevent automoq bugs _mocker.GetMock<FileSystemWatcherBase>(); _fileSystem = new MockFileSystem(); _fileSystem.AddDirectory(BaseDirectory); _mocker.SetInstance<IFileSystem>(_fileSystem); }
public void ReturnsAccessToken() { var mocker = new AutoMoqer(); mocker.GetMock<IOAuthRequest>().Setup(x => x.GrantType).Returns(GrantType.AuthorizationCode); mocker.GetMock<IConfiguration>().Setup(x => x.AuthorizationTokenExpirationLength).Returns(300); mocker.GetMock<IConfiguration>().Setup(x => x.AccessTokenExpirationLength).Returns(500); var issuer = new OAuthIssuer(); mocker.SetInstance<IOAuthIssuer>(issuer); var token = issuer.GenerateAuthorizationToken(new TokenData {ConsumerId = 1, Timestamp = DateTime.UtcNow.Ticks}); mocker.GetMock<IOAuthRequest>().Setup(x => x.AuthorizationCode).Returns(token); var authorizer = mocker.Resolve<AuthorizationCodeAuthorizer>(); var result = authorizer.Authorize(mocker.GetMock<IOAuthRequest>().Object); Assert.IsNotNull(result); Assert.IsTrue(result.AccessToken.HasValue()); Assert.AreEqual(500, result.ExpiresIn); Assert.IsTrue(result.RefreshToken.HasValue()); }
public void WhenAuthorizationCodeHasExpired_ThenThrowException() { var mocker = new AutoMoqer(); mocker.GetMock<IOAuthRequest>().Setup(x => x.GrantType).Returns(GrantType.AuthorizationCode); mocker.GetMock<IConfiguration>().Setup(x => x.AuthorizationTokenExpirationLength).Returns(300); mocker.SetInstance<IOAuthIssuer>(new OAuthIssuer()); var issuer = new OAuthIssuer(); var token = issuer.GenerateAuthorizationToken(new TokenData { ConsumerId = 1, Timestamp = DateTime.UtcNow.AddHours(-1).Ticks }); mocker.GetMock<IOAuthRequest>().Setup(x => x.AuthorizationCode).Returns(token); var authorizer = mocker.Resolve<AuthorizationCodeAuthorizer>(); try { authorizer.Authorize(mocker.GetMock<IOAuthRequest>().Object); Assert.Fail("Exception not thrown"); } catch (OAuthException ex) { Assert.AreEqual(ErrorCode.InvalidRequest, ex.ErrorCode); Assert.IsTrue(ex.ErrorDescription.HasValue()); } }
public void WhenRedirectUriDoesNotMatch_ThenExceptionIsThrown() { var mocker = new AutoMoqer(); mocker.GetMock<IOAuthRequest>().Setup(x => x.GrantType).Returns(GrantType.AuthorizationCode); mocker.GetMock<IConfiguration>().Setup(x => x.AuthorizationTokenExpirationLength).Returns(300); mocker.GetMock<IConfiguration>().Setup(x => x.AccessTokenExpirationLength).Returns(500); var issuer = new OAuthIssuer(); mocker.SetInstance<IOAuthIssuer>(issuer); var token = issuer.GenerateAuthorizationToken(new TokenData { ConsumerId = 1, Timestamp = DateTime.UtcNow.Ticks, RedirectUri = "http://test.com" }); mocker.GetMock<IOAuthRequest>().Setup(x => x.AuthorizationCode).Returns(token); var authorizer = mocker.Resolve<AuthorizationCodeAuthorizer>(); try { authorizer.Authorize(mocker.GetMock<IOAuthRequest>().Object); Assert.Fail("Exception not thrown"); } catch (OAuthException ex) { Assert.AreEqual(ErrorCode.InvalidRequest, ex.ErrorCode); Assert.IsTrue(ex.ErrorDescription.HasValue()); } mocker.GetMock<IOAuthRequest>().Setup(x => x.RedirectUri).Returns("http://test.com"); var result = authorizer.Authorize(mocker.GetMock<IOAuthRequest>().Object); Assert.IsNotNull(result); Assert.IsTrue(result.AccessToken.HasValue()); Assert.AreEqual(500, result.ExpiresIn); Assert.IsTrue(result.RefreshToken.HasValue()); }
public void WhenDataIsValid_ThenNewTokenIsCreated() { var mocker = new AutoMoqer(); mocker.GetMock<IOAuthRequest>().Setup(x => x.ContentType).Returns(ContentType.FormEncoded); mocker.GetMock<IOAuthRequest>().Setup(x => x.ClientId).Returns("clientid"); mocker.GetMock<IOAuthRequest>().Setup(x => x.GrantType).Returns(GrantType.RefreshToken); mocker.GetMock<IConsumerRepository>().Setup(x => x.GetByClientId("clientid")).Returns(new ConsumerImpl { ConsumerId = 12, ClientId = "clientid", Secret = "clientsecret" }); mocker.GetMock<IResourceOwnerRepository>().Setup(x => x.IsConsumerApproved(10, 12)).Returns(true); mocker.GetMock<IOAuthRequest>().Setup(x => x.ClientSecret).Returns("clientsecret"); mocker.SetInstance<IOAuthIssuer>(new OAuthIssuer()); var issuer = new OAuthIssuer(); var authorizer = mocker.Resolve<RefreshTokenRequestAuthorizer>(); var token = issuer.GenerateRefreshToken(new TokenData { ConsumerId = 12, ResourceOwnerId = 10, Timestamp = 1 }); mocker.GetMock<IOAuthRequest>().Setup(x => x.RefreshToken).Returns(token); var newToken = authorizer.Authorize(mocker.GetMock<IOAuthRequest>().Object); Assert.IsNotNull(newToken); var accessTokenData = issuer.DecodeAccessToken(newToken.AccessToken); Assert.IsNotNull(accessTokenData); Assert.AreEqual(10, accessTokenData.ResourceOwnerId); Assert.IsTrue(accessTokenData.Timestamp > DateTimeOffset.UtcNow.AddMinutes(-5).Ticks); var refreshTokenData = issuer.DecodeRefreshToken(newToken.RefreshToken); Assert.IsNotNull(refreshTokenData); Assert.AreEqual(12, refreshTokenData.ConsumerId); Assert.AreEqual(10, refreshTokenData.ResourceOwnerId); Assert.IsTrue(refreshTokenData.Timestamp > DateTimeOffset.UtcNow.AddMinutes(-5).Ticks); }
public void WhenConsumerIsNolongerApproved_ThenThrowsException() { var mocker = new AutoMoqer(); mocker.GetMock<IOAuthRequest>().Setup(x => x.ContentType).Returns(ContentType.FormEncoded); mocker.GetMock<IOAuthRequest>().Setup(x => x.ClientId).Returns("clientid"); mocker.GetMock<IOAuthRequest>().Setup(x => x.GrantType).Returns(GrantType.RefreshToken); mocker.GetMock<IConsumerRepository>().Setup(x => x.GetByClientId("clientid")).Returns(new ConsumerImpl { ConsumerId = 12, ClientId = "clientid", Secret = "clientsecret" }); mocker.GetMock<IResourceOwnerRepository>().Setup(x => x.IsConsumerApproved(10, 12)).Returns(false); mocker.GetMock<IOAuthRequest>().Setup(x => x.ClientSecret).Returns("clientsecret"); mocker.SetInstance<IOAuthIssuer>(new OAuthIssuer()); var issuer = new OAuthIssuer(); var authorizer = mocker.Resolve<RefreshTokenRequestAuthorizer>(); var token = issuer.GenerateRefreshToken(new TokenData { ConsumerId = 12, ResourceOwnerId = 10, Timestamp = 1 }); mocker.GetMock<IOAuthRequest>().Setup(x => x.RefreshToken).Returns(token); try { authorizer.Authorize(mocker.GetMock<IOAuthRequest>().Object); Assert.Fail("Exception not thrown"); } catch (OAuthException ex) { Assert.AreEqual(ErrorCode.UnauthorizedClient, ex.ErrorCode); Assert.IsTrue(!string.IsNullOrWhiteSpace(ex.ErrorDescription)); } }
public void Create_with_constant_concerete_dependency_uses_constant() { //Arrange var mocker = new AutoMoqer(); var constant = new VirtualDependency() { PropValue = Guid.NewGuid().ToString() }; mocker.SetInstance(constant); //Act var result = mocker.Create<ClassWithVirtualDependencies>().GetVirtualProperty(); //Assert Assert.AreEqual((object) constant.PropValue, result); }
public void Registering_instance_for_Interface_injects_that_Instance() { //Arrange var mocker = new AutoMoqer(); var instance = new Dependency(); mocker.SetInstance<IDependency>(instance); //Act var result = mocker.Create<ClassWithDependencies>().Dependency; //Assert Assert.AreEqual(instance, result); }