Пример #1
1
        public async Task EfetuaPagamento_Test()
        {
            //Given
            var mocker           = new AutoMoqer();
            var baseExternalMock = mocker.Create <GatewayExternalService>();


            var Cartao = new AutoFaker <CartaoEntity>()
                         .RuleFor(fake => fake.Bandeira, fake => PagamentoBandeiraEnum.MasterCard)
                         .RuleFor(fake => fake.DataValidade, fake => fake.Date.Future(2))
                         .RuleFor(fake => fake.Tipo, fake => TipoCartaoEnum.Credito)
                         .Generate();

            var param = new AutoFaker <PagamentoEntity>()
                        .RuleFor(fake => fake.StatusPagamento, fake => fake.PickRandom <StatusPagamentoEnum>())
                        .RuleFor(fake => fake.Cartao, fake => Cartao)
                        .Generate();

            var expectResponse = new GatewayDTO
            {
                IdPedido        = param.IdPedido,
                StatusPagamento = StatusPagamentoEnum.Aprovado
            };

            var response = new GatewayExternalDTO
            {
                StatusPagamento = StatusPagamentoEnum.Aprovado
            };


            var externalContext = mocker.GetMock <IGatewayExternalContext>();

            externalContext.Setup(e => e.EfetuarPagamentoCartao(It.IsAny <GatewayCartaoParam>())).ReturnsAsync(response).Verifiable();

            //When
            var result = await baseExternalMock.EfetuaPagamento(param);

            //Then
            var comparison = new CompareLogic();

            externalContext.Verify(mock => mock.EfetuarPagamentoCartao(It.IsAny <GatewayCartaoParam>()), Times.Once());
            Assert.True(comparison.Compare(result, expectResponse).AreEqual);
        }
Пример #2
0
        public void creating_the_child_twice()
        {
            var autoMoq = new AutoMoqer();

            autoMoq.Create<Child>();
            autoMoq.Create<Child>();
        }
Пример #3
0
        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);
        }
Пример #4
0
        public void I_can_instantiate_a_working_automoqer_with_no_dependencies()
        {
            var mocker = new AutoMoqer();

            var bar = mocker.Create<Bar>();
            bar.Foo.ShouldBeSameAs(mocker.GetMock<IFoo>().Object);
        }
        public void SetUp()
        {
            var customer = new Customer
            {
                Name = CustomerName
            };

            var employee = new Employee
            {
                Name = EmployeeName
            };

            var product = new Product
            {
                Name = ProductName
            };

            _sale = new Sale()
            {
                Id = SaleId,
                Date = Date,
                Customer = customer,
                Employee = employee,
                Product = product,
                UnitPrice = UnitPrice,
                Quantity = Quantity,
                TotalPrice = TotalPrice
            };

            _mocker = new AutoMoqer();

            _query = _mocker.Create<GetSalesListQuery>();
        }
Пример #6
0
        public void ItSendsBackSomeRss(ComicType type)
        {
            var mocker = new AutoMoqer();
            mocker.GetMock<IComicsRepository>()
                .Setup(m => m.GetLatestComics(type, 10))
                .Returns(new[]
                {
                    new Comic()
                    {
                        ComicNumber = 1,
                        ComicType = type,
                        ImageSrc = "http://example.com/image.png",
                        Permalink = "http://example.com",
                        ComicId = 1,
                        PublishedDate = DateTime.Today
                    }
                });

            var result = mocker.Create<FeedController>().Feed(type);

            var s = new MemoryStream();
            result.FileStream.CopyTo(s);
            var xml = Encoding.UTF8.GetString(s.ToArray());

            Check.That(result.ContentType).IsEqualTo("text/xml");
            Check.That(xml).Contains("http://example.com/image.png");
        }
Пример #7
0
        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);
        }
Пример #8
0
        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);
        }
Пример #9
0
        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);
        }
Пример #10
0
        public void WhenAuthorizedReturnsContentResult()
        {
            var mocker = new AutoMoqer();
            mocker.GetMock<IImportProcess>()
                .Setup(m => m.ImportedComics)
                .Returns(new Comic[] {});

            var result = mocker.Create<AdminController>().Refresh(authToken: ConfigurationManager.AppSettings["AdminAuthToken"]);

            Check.That(result).IsInstanceOf<ContentResult>();
        }
        public void SetUp()
        {
            _model = new CustomerModel();

            _mocker = new AutoMoqer();

            _mocker.GetMock<IGetCustomersListQuery>()
                .Setup(p => p.Execute())
                .Returns(new List<CustomerModel> { _model });

            _controller = _mocker.Create<CustomersController>();
        }
Пример #12
0
        public void I_can_replace_the_unity_container_with_my_own()
        {
            var container = new UnityContainer();

            var foo = new Mock<IFoo>().Object;
            container.RegisterInstance(foo);

            var mocker = new AutoMoqer(container);

            var bar = mocker.Create<Bar>();
            bar.Foo.ShouldBeSameAs(foo);
        }
        public void SetUp()
        {
            _model = new EmployeeModel();

            _mocker = new AutoMoqer();

            _mocker.GetMock<IGetEmployeesListQuery>()
                .Setup(p => p.Execute())
                .Returns(new List<EmployeeModel> { _model });

            _controller = _mocker.Create<EmployeesController>();
        }
        public void SetUp()
        {
            _model = new ProductModel();

            _mocker = new AutoMoqer();

            _mocker.GetMock<IGetProductsListQuery>()
                .Setup(p => p.Execute())
                .Returns(new List<ProductModel> { _model });

            _controller = _mocker.Create<ProductsController>();
        }
Пример #15
0
        public void ItRunsTheImports()
        {
            var mocker = new AutoMoqer();
            mocker.GetMock<IImportProcess>()
                .Setup(m => m.ImportedComics)
                .Returns(new Comic[] {});

            mocker.Create<AdminController>().Refresh(authToken: ConfigurationManager.AppSettings["AdminAuthToken"]);

            mocker.GetMock<IImportProcess>()
                .Verify(m => m.Run(), Times.Once);
        }
Пример #16
0
        public void ItSearchesForTheReferencedComic(ComicType type)
        {
            var mocker = new AutoMoqer();
            mocker.GetMock<IComicsRepository>()
                .Setup(m => m.GetLatestComics(type, It.IsAny<int>()))
                .Returns(Enumerable.Empty<Comic>().ToList())
                .Verifiable();

            mocker.Create<FeedController>().Feed(type);

            mocker.GetMock<IComicsRepository>().Verify();
        }
Пример #17
0
        public void Can_a_mock_generated_by_automoq_be_called_twice()
        {
            var mocker = new AutoMoqer();

            var id = "the id";
            var profile = new Profile();
            var profiles = mocker.Create<SomeController>();

            mocker.GetMock<IProfilerGetter>().Setup(p => p.Get(id)).Returns(profile);
            var p1 = profiles.Get(id);
            var p2 = profiles.Get(id);
            Assert.IsNotNull(p1);
            Assert.IsNotNull(p2);
        }
Пример #18
0
        public void ItHasRudimentarySecurity()
        {
            //Requires appsetting: AdminAuthToken
            var mocker = new AutoMoqer();

            Check.That(ConfigurationManager.AppSettings["AdminAuthToken"]).IsNotEmpty();
            Check.That(ConfigurationManager.AppSettings["AdminAuthToken"]).IsNotNull();

            var result = mocker.Create<AdminController>().Refresh(authToken: "foobar");

            Check.That(ConfigurationManager.AppSettings["AdminAuthToken"]).IsNotEmpty();
            Check.That(ConfigurationManager.AppSettings["AdminAuthToken"]).IsNotNull();
            Check.That(ConfigurationManager.AppSettings["AdminAuthToken"]).IsNotEqualTo("foobar");
            Check.That(result).IsInstanceOf<HttpUnauthorizedResult>();
        }
Пример #19
0
        public async Task Criar_test()
        {
            var mocker          = new AutoMoqer();
            var baseCommandMock = mocker.Create <UsuarioCommand>();

            var param = new AutoFaker <UsuarioParam>()
                        .RuleFor(fake => fake.Role, fake => fake.PickRandom <RoleEnum>().ToString())
                        .Generate();

            var usuarioRepoMock = mocker.GetMock <IUsuariosRepository>();

            usuarioRepoMock.Setup(u => u.Inserir(It.IsAny <UsuarioEntity>())).Returns(Task.Factory.StartNew(() => string.Empty)).Verifiable();

            await baseCommandMock.Criar(param);


            usuarioRepoMock.Verify(u => u.Inserir(It.IsAny <UsuarioEntity>()), Times.Once);
        }
Пример #20
0
        public void CreatedInstanceHasRegisteredMock()
        {
            // arrange
            var target   = new AutoMoqer();
            var expected = new Customer(1, "John");

            target.GetMock <ICustomerRepository>()
            .Setup(r => r.GetById(expected.Id))
            .Returns(expected);

            // act
            var result = target.Create <CustomerRepositoryContainer>()
                         .CustomerRepository
                         .GetById(expected.Id);

            // assert
            Assert.Equal(expected, result);
        }
Пример #21
0
        public void I_can_replace_the_unity_container_with_my_own_through_config()
        {
            var container = new UnityContainer();
            var config    = new Config()
            {
                Container = container
            };

            var foo = new Mock <IFoo>().Object;

            container.RegisterInstance(foo);

            var mocker = new AutoMoqer(config);

            var bar = mocker.Create <Bar>();

            bar.Foo.ShouldBeSameAs(foo);
        }
Пример #22
0
        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);
        }
Пример #23
0
        public void SetUp()
        {
            _mocker = new AutoMoqer();

            _searchResult = new SearchResult
            {
                Rank = Rank,
                Url  = Url
            };

            _mocker.GetMock <ISearchClient>()
            .Setup(u => u.SearchAsync(It.IsAny <string>(), It.IsAny <int>()))
            .ReturnsAsync(new List <SearchResult> {
                _searchResult
            });

            _googleSearchService = _mocker.Create <GoogleSearchService>();
        }
Пример #24
0
        public void SetUp()
        {
            _mocker = new AutoMoqer();

            _mockAnchor = new Mock <IAnchor>();

            _mockAnchor.Setup(p => p.GetHref())
            .Returns(ChildUrl);

            _anchors = new List <IAnchor>()
            {
                _mockAnchor.Object
            };

            _mocker.GetMock <ILinkDictionary>()
            .Setup(p => p.HasLink(Url))
            .Returns(false);

            _mocker.GetMock <IWebClientWrapper>()
            .Setup(p => p.DownloadString(Url))
            .Returns(Html);

            _mocker.GetMock <IHtmlDocumentWrapper>()
            .Setup(p => p.GetAnchors(Html))
            .Returns(_anchors);

            _mocker.GetMock <IWebsite>()
            .Setup(p => p.IsMailToUrl(ChildUrl))
            .Returns(false);

            _mocker.GetMock <IWebsite>()
            .Setup(p => p.IsSiteRelativeUrl(ChildUrl))
            .Returns(false);

            _mocker.GetMock <IWebsite>()
            .Setup(p => p.IsPageRelativeUrl(ChildUrl))
            .Returns(false);

            _mocker.GetMock <IWebClientWrapper>()
            .Setup(p => p.DownloadString(ChildUrl))
            .Returns(Html);

            _checker = _mocker.Create <PageChecker>();
        }
        public void SetUp()
        {
            _mocker = new AutoMoqer();
            _query  = _mocker.Create <GetCustomerListQuery>();

            var customer = new Customer
            {
                Id          = CustomerId,
                Name        = CustomerName,
                PhoneNumber = CustomerPhoneNumber
            };

            var customerList = new List <Customer> {
                customer
            };

            _mocker.GetMock <ICustomerRepository>()
            .Setup(pr => pr.GetAll()).Returns(customerList.AsQueryable());
        }
        public void OnDock_SuccessfullyDocked()
        {
            // Arrange
            var automoq = new AutoMoqer();

            var dockerController = automoq.Create <DockerController>();

            var dockRepository = automoq.GetMock <IDockRepository>();

            dockRepository.Setup(x => x.Dock(It.IsAny <Shuttle>())).Returns(Task.FromResult(true));



            // Act
            var result = dockerController.Dock(new Models.Models.Shuttle()) as OkResult;

            // Assert
            result?.StatusCode.Should().Be((int)HttpStatusCode.OK);
        }
Пример #27
0
        public void SetUp()
        {
            _mocker = new AutoMoqer();
            _query  = _mocker.Create <GetPartnersListQuery>();

            var partner = new Partner
            {
                Id          = PartnerId,
                Name        = PartnerName,
                PhoneNumber = PartnerPhoneNumber
            };

            var partnerList = new List <Partner> {
                partner
            };

            _mocker.GetMock <IPartnersRepository>()
            .Setup(pr => pr.GetAll()).Returns(partnerList.AsQueryable());
        }
Пример #28
0
        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 Setup()
        {
            _mocker = new AutoMoqer();

            _applicant = new Applicant()
            {
                ID           = Id,
                EMailAddress = Email
            };

            // _mocker.GetMock<DbSet<Applicant>>()
            //     .SetUpDbSet(new List<Applicant> { _applicant });

            _mocker.GetMock <ApplicationContext>()
            .Setup(p => p.Applicants)
            .Returns(_mocker.GetMock <Microsoft.EntityFrameworkCore.DbSet <Applicant> >().Object);

            _query = _mocker.Create <ApplicantRepository>();
        }
Пример #30
0
        public void SetUp()
        {
            _mocker = new AutoMoqer();

            var customer = new CustomerModel
            {
                Id   = CustomerId,
                Name = CustomerName,
            };

            var employee = new EmployeeModel()
            {
                Id   = EmployeeId,
                Name = EmployeeName
            };

            var product = new ProductModel
            {
                Id        = ProductId,
                Name      = ProductName,
                UnitPrice = ProductPrice
            };

            _mocker.GetMock <IGetCustomersListQuery>()
            .Setup(p => p.Execute())
            .Returns(new List <CustomerModel> {
                customer
            });

            _mocker.GetMock <IGetEmployeesListQuery>()
            .Setup(p => p.Execute())
            .Returns(new List <EmployeeModel> {
                employee
            });

            _mocker.GetMock <IGetProductsListQuery>()
            .Setup(p => p.Execute())
            .Returns(new List <ProductModel> {
                product
            });

            _factory = _mocker.Create <CreateSaleViewModelFactory>();
        }
Пример #31
0
        public void Setup()
        {
            _invoice = new Invoice()
            {
                Id    = invoiceId,
                Total = total
            };
            _mocker = new AutoMoqer();

            _mocker.GetMock <IDatabase>()
            .Setup(p => p.GetInvoice(invoiceId))
            .Returns(_invoice);

            _mocker.GetMock <IDateTimeWrapper>()
            .Setup(p => p.GetNow())
            .Returns(new System.DateTime());

            _invoicePrinter = _mocker.Create <NewPrintInvoiceCommand>();
        }
Пример #32
0
        public void Reproduce_the_issue()
        {
            var cookies = new HttpCookieCollection();
            cookies.Add(new HttpCookie("foo", "bar"));

            var auto = new AutoMoqer();
            var httpRequestBase = auto.GetMock<HttpRequestBase>().Object;
            auto.GetMock<HttpContextBase>()
                .Setup(x => x.Request)
                .Returns(httpRequestBase);

            auto.GetMock<HttpRequestBase>()
                .SetupGet(x => x.Cookies)
                .Returns(cookies);

            var svc = auto.Create<ContextService>();
            var hascookie = svc.HasCookie("foo");
            Assert.IsTrue(hascookie);
        }
Пример #33
0
        public async Task readBody_StateUnderTest_ExpectedBehavior()
        {
            // Arrange
            var mocker        = new AutoMoqer();
            var unitUnderTest = mocker.Create <WxXmlHelp>();

            var    bytes  = System.Text.Encoding.UTF8.GetBytes(xml);
            Stream stream = new MemoryStream(bytes);

            stream.Position = 0;


            // Act
            var result = await unitUnderTest.ReadBody(
                stream);

            // Assert
            Assert.AreEqual(result, xml);
        }
Пример #34
0
        public void ReturnResultFromRandom()
        {
            var mocker = new AutoMoqer();

            mocker.GetMock <Random>()
            .Setup(x => x.Next(It.IsAny <int>(), It.IsAny <int>()))
            .Returns(5);

            var service = mocker.Create <RollDieService>();

            var die    = new SixSidedDie();
            var result = service.Handle(new RollDieRequest {
                Die = die
            }, CancellationToken.None).Result;

            Assert.IsNotNull(result);
            Assert.AreEqual(die, result.Die);
            Assert.AreEqual(5, result.Value);
        }
Пример #35
0
        public async void ConsultaDrone_Test()
        {
            var mocker        = new AutoMoqer();
            var baseQueryMock = mocker.Create <DroneQuery>();

            var faker = AutoFaker.Create();

            var responseDroneRepo   = faker.Generate <List <DroneEntity> >();
            var responseUsuarioRepo = faker.Generate <UsuarioEntity>();
            var responsePedidosRepo = new List <PedidoEntity>
            {
                new AutoFaker <PedidoEntity>()
                .RuleFor(fake => fake.Drone, fake => responseDroneRepo[0])
                .RuleFor(fake => fake.DroneId, fake => responseDroneRepo[0].Id)
                .RuleFor(fake => fake.CompradorId, fake => responseUsuarioRepo.Id)
                .Generate()
            };


            var expectResponse = ExpectResponseDroneQueryList(responseDroneRepo, responsePedidosRepo, responseUsuarioRepo);;

            var droneRepoMock   = mocker.GetMock <IDronesRepository>();
            var pedidosRepoMock = mocker.GetMock <IPedidosRepository>();
            var usuarioRepoMock = mocker.GetMock <IUsuariosRepository>();

            droneRepoMock.Setup(r => r.GetAll()).ReturnsAsync(responseDroneRepo).Verifiable();
            pedidosRepoMock.Setup(r => r.GetByDroneID(responseDroneRepo[0].Id)).ReturnsAsync(responsePedidosRepo).Verifiable();
            usuarioRepoMock.Setup(r => r.GetSingleById(responseUsuarioRepo.Id)).ReturnsAsync(responseUsuarioRepo).Verifiable();

            //When

            var result = await baseQueryMock.ConsultaDrone();

            //Then
            var comparison = new CompareLogic();

            droneRepoMock.Verify(mock => mock.GetAll(), Times.Once());
            pedidosRepoMock.Verify(mock => mock.GetByDroneID(It.IsAny <Guid>()), Times.Exactly(3));
            usuarioRepoMock.Verify(mock => mock.GetSingleById(It.IsAny <Guid>()), Times.Once());
            var comp = comparison.Compare(result, expectResponse);

            Assert.True(comp.AreEqual);
        }
        public void SetUp()
        {
            _mocker = new AutoMoqer();
            _query  = _mocker.Create <GetProductsListQuery>();

            var product = new Product
            {
                Id        = ProductId,
                Name      = ProductName,
                UnitPrice = ProductUnitPrice
            };

            var productList = new List <Product> {
                product
            };

            _mocker.GetMock <IProductRepository>()
            .Setup(pr => pr.GetAll()).Returns(productList.AsQueryable());
        }
        public void SetUp()
        {
            _mocker = new AutoMoqer();

            _product = new Product()
            {
                Id = Id,
                Name = Name
            };

            _mocker.GetMock<IDbSet<Product>>()
                .SetUpDbSet(new List<Product> { _product });

            _mocker.GetMock<IDatabaseContext>()
                .Setup(p => p.Products)
                .Returns(_mocker.GetMock<IDbSet<Product>>().Object);

            _query = _mocker.Create<GetProductsListQuery>();
        }
        public void SetUp()
        {
            _mocker = new AutoMoqer();

            _employee = new Employee()
            {
                Id = Id,
                Name = Name
            };

            _mocker.GetMock<IDbSet<Employee>>()
                .SetUpDbSet(new List<Employee> { _employee });

            _mocker.GetMock<IDatabaseContext>()
                .Setup(p => p.Employees)
                .Returns(_mocker.GetMock<IDbSet<Employee>>().Object);

            _query = _mocker.Create<GetEmployeesListQuery>();
        }
Пример #39
0
        public void CreateSign_SHA256_StateUnderTest_ExpectedBehavior()
        {
            var mocker = new AutoMoqer();

            mocker.GetMock <IOptions <WxConfig> >().Setup(x => x.Value).Returns(new WxConfig()
            {
                PayKey   = "192006250b4c09247ec02edce69f6a2d",
                SignMode = SignMode.HmacSHA256
            });

            var unitUnderTest = mocker.Create <WxXmlHelp>();

            var todo   = unitUnderTest.ReadFromXml <PayCallbackData>(xml);
            var newxml = unitUnderTest.WriteToXml(todo);

            var sign = unitUnderTest.CreateSign(todo);

            Assert.AreEqual("90C202674D0F1E0C2B1755FD1FE175B810760C02EB14B2B414B0971E5BD6CDD7", sign);
        }
        public void ReturnProperData_GetHighScoresApi()
        {
            //arrange
            var Database         = _mock.Create <DatabaseService>();
            var MockedController = _mock.Create <HighScoreOrchestrator>();

            var DataToTest = Database.GenerateData();

            //act
            var SortedDataToCheck = MockedController.GetScores(DataToTest);

            bool TestResult = false;

            if (SortedDataToCheck[0].Score >= SortedDataToCheck[1].Score && SortedDataToCheck[1].Score >= SortedDataToCheck[2].Score)
            {
                TestResult = true;
            }

            //assert
            Assert.IsTrue(TestResult);
        }
Пример #41
0
        public void TryInvokeMember_StateUnderTest_ExpectedBehavior()
        {
            // Arrange
            var mocker   = new AutoMoqer();
            var logProxy = mocker.Create <LogProxy>();
            InvokeMemberBinder binder = null;

            object[] args   = null;
            object   result = null;

            // Act
            result = logProxy.TryInvokeMember(
                binder,
                args,
                out result);

            // Assert
            Assert.True(false);
        }
        public void SetUp()
        {
            _mocker = new AutoMoqer();

            _customer = new Customer()
            {
                Id = Id,
                Name = Name
            };

            _mocker.GetMock<IDbSet<Customer>>()
                .SetUpDbSet(new List<Customer> { _customer });

            _mocker.GetMock<IDatabaseContext>()
                .Setup(p => p.Customers)
                .Returns(_mocker.GetMock<IDbSet<Customer>>().Object);

            _query = _mocker.Create<GetCustomersListQuery>();
        }
Пример #43
0
        public void SetUp()
        {
            _invoice = new Invoice()
            {
                Id    = InvoiceId,
                Total = Total
            };

            _mocker = new AutoMoqer();

            _mocker.GetMock <IDatabase>()
            .Setup(p => p.GetInvoice(InvoiceId))
            .Returns(_invoice);

            _mocker.GetMock <IDateTimeWrapper>()
            .Setup(p => p.GetNow())
            .Returns(Date);

            _command = _mocker.Create <PrintInvoiceCommand>();
        }
Пример #44
0
        public void CreateSign_MD5_StateUnderTest_ExpectedBehavior()
        {
            var mocker = new AutoMoqer();

            mocker.GetMock <IOptions <WxConfig> >().Setup(x => x.Value).Returns(new WxConfig()
            {
                PayKey   = "192006250b4c09247ec02edce69f6a2d",
                SignMode = SignMode.MD5
            });

            var unitUnderTest = mocker.Create <WxXmlHelp>();

            var todo   = unitUnderTest.ReadFromXml <PayCallbackData>(xml);
            var newxml = unitUnderTest.WriteToXml(todo);

            var sign = unitUnderTest.CreateSign(todo);


            Assert.AreEqual("424A19186D0092B11404CF00E0B15265", sign);
        }
        public void Should_Ensure_Microsoft_CodeCoverage_Is_Unzipped_To_The_Tool_Folder()
        {
            var autoMocker = new AutoMoqer();
            var msCodeCoverageRunSettingsService = autoMocker.Create <MsCodeCoverageRunSettingsService>();

            var cancellationToken = CancellationToken.None;

            var zipDetails          = new ZipDetails();
            var mockToolZipProvider = autoMocker.GetMock <IToolZipProvider>();

            mockToolZipProvider.Setup(toolZipProvider => toolZipProvider.ProvideZip("microsoft.codecoverage")).Returns(zipDetails);

            var mockToolFolder = autoMocker.GetMock <IToolFolder>();

            mockToolFolder.Setup(toolFolder =>
                                 toolFolder.EnsureUnzipped("AppDataFolder", "msCodeCoverage", zipDetails, cancellationToken)).Returns("ZipDestination");

            msCodeCoverageRunSettingsService.Initialize("AppDataFolder", null, cancellationToken);
            mockToolFolder.VerifyAll();
        }
        public void SetUp()
        {
            _invoice = new Invoice();

            _mocker = new AutoMoqer();

            _mocker.GetMock <IDatabase>().
            Setup(p => p.GetInvoice(InvoiceId))
            .Returns(_invoice);

            _mocker.GetMock <ISecurity>()
            .Setup(p => p.IsAdmin())
            .Returns(true);

            _mocker.GetMock <ISecurity>()
            .Setup(p => p.GetUserName())
            .Returns(UserName);

            _command = _mocker.Create <PrintOrEmailInvoiceCommand>();
        }
Пример #47
0
        public void SetUp()
        {
            _mocker = new AutoMoqer();

            _employee = new Employee()
            {
                Id   = Id,
                Name = Name
            };

            var employeeMock = CreateDbSetMock.SetUpDbSet(new List <Employee> {
                _employee
            }.AsQueryable());

            _mocker.GetMock <IDatabaseService>()
            .Setup(p => p.Employees)
            .Returns(employeeMock.Object);

            _query = _mocker.Create <GetEmployeesListQuery>();
        }
Пример #48
0
        public async Task GivenAProductService_WhenGettingProducts()
        {
            var moqer          = new AutoMoqer();
            var productService = moqer.Create <ProductService>();

            _productRepository = moqer.GetMock <IProductRepository>();
            _mapper            = moqer.GetMock <IMapper>();

            var fixture           = new Fixture();
            var cancellationToken = new CancellationToken();

            var productDataModelsResult = new Result <List <DAL.DataModels.Product> >(fixture.CreateMany <DAL.DataModels.Product>().ToList());

            _productRepository.Setup(x => x.GetProducts(cancellationToken)).Returns(Task.FromResult(productDataModelsResult)).Verifiable();

            _mappedProducts = fixture.CreateMany <Product>().ToList();
            _mapper.Setup(x => x.Map <List <Product> >(productDataModelsResult.Value)).Returns(_mappedProducts).Verifiable();

            _result = await productService.GetProducts(cancellationToken);
        }
Пример #49
0
        public void SetUp()
        {
            _mocker = new AutoMoqer();

            _sale = new Sale()
            {
                Id = SaleId
            };

            _sales = new InMemoryDbSet <Sale>()
            {
                _sale
            };

            _mocker.GetMock <IDatabaseContext>()
            .Setup(p => p.Set <Sale>())
            .Returns(_sales);

            _repository = _mocker.Create <Repository <Sale> >();
        }
        public async Task RetrieveByIdAsync_ShouldReturnItemForGivenId()
        {
            // Arrange
            var item = new Item(Guid.NewGuid().ToString());

            var sut = _mocker.Create <ItemsWriteService>();

            var validatorMock = _mocker.GetMock <IItemValidator>();

            var repositoryMock = _mocker.GetMock <IItemsRepository>();

            repositoryMock.Setup(s => s.InsertAsync(It.IsAny <Item>())).ReturnsAsync(true);

            // Act
            var result = await sut.InsertAsync(item).ConfigureAwait(false);

            // Assert
            validatorMock.Verify(v => v.ValidateEntityAndThrowAsync(It.Is <Item>(p => p == item)), Times.Once);
            repositoryMock.Verify(v => v.InsertAsync(It.Is <Item>(p => p == item)), Times.Once);
        }
        public void EmployeeControllerTests_ConstructorShouldReturnList_No_Error()
        {
            var employee = new EmployeeModel()
            {
                Id = 1, Name = "William Han"
            };

            _mocker.GetMock <IGetEmployeesListQuery>()
            .Setup(p => p.Execute())
            .Returns(new List <EmployeeModel> {
                employee
            });

            _query = _mocker.Create <IGetEmployeesListQuery>();
            var controller = new EmployeesController(_query);
            //System.Web.Http.Results.OkNegotiatedContentResult<System.Collections.Generic.IEnumerable<Application.Employees.Queries.EmployeeModel>>
            var results = controller.Get() as System.Web.Http.Results.OkNegotiatedContentResult <System.Collections.Generic.IEnumerable <EmployeeModel> >;

            Assert.AreEqual(results.Content.ToList().Single(), employee);
        }
        public void ShouldWriteSequence()
        {
            const string sequenceString = "SomeString";
            var sequence = new object[] {1, 2, 3};

            var mocker = new AutoMoqer();
            var sut = mocker.Create<FizzBuzzMediator>();

            mocker.GetMock<IFizzBuzzSequenceGenerator>()
                .Setup(x => x.GenerateFizzBuzzSequence(1, 3))
                .Returns(sequence);

            mocker.GetMock<IFizzBuzzFormatter>()
                .Setup(x => x.FormatFizzBuzzSequence(sequence))
                .Returns(sequenceString);

            sut.GenerateFizzBuzzSequence(1,3);

            mocker.GetMock<TextWriter>()
                  .Verify(x => x.WriteLine(sequenceString));
        }
Пример #53
0
        public void It_should_allow_a_mock_to_be_changed_on_a_mock_by_mock_basis()
        {
            var mocker = new AutoMoqer();

            mocker.GetMock<IFoo>(MockBehavior.Loose);
            mocker.GetMock<IFooFoo>(MockBehavior.Strict);

            var bar = mocker.Create<BarBar>();

            bar.ThrowFoo(); // this one is loose, so it should not throw

            var anErrorWasThrown = false;
            try
            {
                bar.ThrowFooFoo(); // this one is strict, so it should throw
            }
            catch
            {
                anErrorWasThrown = true;
            }
            anErrorWasThrown.ShouldBeTrue();
        }
        public void SetUp()
        {
            _mocker = new AutoMoqer();

            var customer = new CustomerModel
            {
                Id = CustomerId,
                Name = CustomerName,
            };

            var employee = new EmployeeModel()
            {
                Id = EmployeeId,
                Name = EmployeeName
            };

            var product = new ProductModel
            {
                Id = ProductId,
                Name = ProductName,
                UnitPrice = ProductPrice
            };

            _mocker.GetMock<IGetCustomersListQuery>()
                .Setup(p => p.Execute())
                .Returns(new List<CustomerModel> { customer });

            _mocker.GetMock<IGetEmployeesListQuery>()
                .Setup(p => p.Execute())
                .Returns(new List<EmployeeModel> { employee });

            _mocker.GetMock<IGetProductsListQuery>()
                .Setup(p => p.Execute())
                .Returns(new List<ProductModel> { product });

            _factory = _mocker.Create<CreateSaleViewModelFactory>();
        }
Пример #55
0
 public void SetUp()
 {
     _mocker = new AutoMoqer();
     _socApp = _mocker.Create<SocApp>();
     _postStore = _mocker.GetMock<IPostStore>();
     _followStore = _mocker.GetMock<IFollowStore>();
 }
Пример #56
0
        public void Create_with_dependency_doesnt_return_mock()
        {
            //Arrange
            var mocker = new AutoMoqer();

            //Act
            var result = mocker.Create<VirtualDependency>().VirtualMethod();

            //Assert
            Assert.AreEqual("hello", result);
        }
Пример #57
0
        public void Create_with_mocked_dependency_uses_mock()
        {
            //Arrange
            var mocker = new AutoMoqer();

            mocker.GetMock<VirtualDependency>()
                .Setup(m => m.VirtualMethod())
                .Returns("mocked");

            //Act
            var result = mocker.Create<ClassWithVirtualDependencies>().CallVirtualChild();

            //Assert
            Assert.AreEqual("mocked", result);
        }
Пример #58
0
        public void Create_with_unbound_concerete_dependency_uses_mock()
        {
            //Arrange
            var mocker = new AutoMoqer();

            //Act
            var result = mocker.Create<ClassWithVirtualDependencies>().CallVirtualChild();

            var mockedResult = new Mock<VirtualDependency>().Object.VirtualMethod();

            //Assert
            Assert.AreEqual((object) mockedResult, result);
        }
Пример #59
0
        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);
        }
Пример #60
0
        public void Create_doesnt_return_mock()
        {
            //Arrange
            var mocker = new AutoMoqer();

            //Act
            var result = mocker.Create<ConcreteClass>().Do();

            //Assert
            Assert.AreEqual("hello", result);
        }