Example #1
0
        public void Promote_Should_Use_DomainObjectFactory_And_VoteRepository()
        {
            var user = new User {
                Id = Guid.NewGuid()
            };
            var at            = SystemTime.Now();
            var fromIpAddress = "192.168.0.1";

            domainObjectFactory.Setup(r => r.CreateStoryVote(_story, at, user, fromIpAddress)).Returns(new StoryVote()).Verifiable();

            _story.Promote(at, user, fromIpAddress);

            domainObjectFactory.Verify();
            voteRepository.Verify(r => r.Add(It.IsAny <StoryVote>()), Times.AtMostOnce());
        }
Example #2
0
        public void Demote_Should_Use_VoteRepository()
        {
            _story.User = new User {
                Id = Guid.NewGuid()
            };

            voteRepository.Setup(r => r.FindById(It.IsAny <Guid>(), It.IsAny <Guid>())).Returns(new StoryVote()).Verifiable();

            _story.Demote(SystemTime.Now(), new User {
                Id = Guid.NewGuid()
            });

            voteRepository.Verify(r => r.Remove(It.IsAny <StoryVote>()), Times.AtMostOnce());
            voteRepository.Verify();
        }
Example #3
0
        public void Given_UseIdAndPassword_WhenPasswordChange_ThenPasswordChange()
        {
            //Arrage
            var user = GetUser();

            _mockUserRepository.Setup(m => m.Count(It.IsAny <Func <User, bool> >())).Returns(1);
            _mockUserRepository.Setup(m => m.Get(It.IsAny <Expression <Func <User, bool> > >())).Returns(user);
            _mockUserRepository.Setup(m => m.Update(user.Id.ToString(), user));
            //act
            _userDomain.ChangePassord(user.Id, user.Password);
            //Asert
            _mockUserRepository.Verify(x => x.Count(It.IsAny <Func <User, bool> >()), Times.AtMostOnce());
            _mockUserRepository.Verify(x => x.Get(It.IsAny <Expression <Func <User, bool> > >()), Times.AtMostOnce());
            _mockUserRepository.Verify(x => x.Update(user.Id.ToString(), user), Times.AtMostOnce());
        }
        public void ApplyDatabase_should_run_targeted_model_conventions()
        {
            var database                 = new EdmModel().Initialize();
            var table                    = database.AddTable("T");
            var mockConvention           = new Mock <IDbConvention <EntityType> >();
            var conventionsConfiguration = new ConventionsConfiguration(
                new IConvention[]
            {
                mockConvention.Object
            });

            conventionsConfiguration.ApplyDatabase(database);

            mockConvention.Verify(c => c.Apply(table, database), Times.AtMostOnce());
        }
Example #5
0
        public void Moq_AnalyzeData_SaveDataMethodShouldBeCalledBecauseTemperatureIsRight(TemperatureLevel saveDataLevel, float temperature)
        {
            client.Setup(i => i.GetTemperature()).Returns(temperature);
            saver.Setup(d => d.SaveData(It.IsAny <float>()));

            var analyzer = new GreenHouseAnalyzer(
                saveDataLevel: saveDataLevel,
                logMessageLevel: TemperatureLevel.All,
                fakeDataSaver: saver.Object,
                fakeGreenHouseClient: client.Object);

            analyzer.AnalyzeData();

            saver.Verify(d => d.SaveData(temperature), Times.AtMostOnce());
        }
Example #6
0
        public void ThrowsIfVerifySetAtMostOnceAndMoreThanOneCall()
        {
            var mock = new Mock <IFoo>();

            mock.Object.Value = 3;

            mock.VerifySet(f => f.Value = 3, Times.AtMostOnce());

            mock.Object.Value = 3;

            MockException mex = Assert.Throws <MockException>(
                () => mock.VerifySet(f => f.Value = 3, Times.AtMostOnce()));

            Assert.Equal(MockException.ExceptionReason.VerificationFailed, mex.Reason);
        }
Example #7
0
        public void ThrowsIfVerifyReturningAtMostOnceAndMoreThanOneCall()
        {
            var mock = new Mock <IFoo>();

            mock.Object.Execute("");

            mock.Verify(foo => foo.Execute(""), Times.AtMostOnce());

            mock.Object.Execute("");

            MockException mex = Assert.Throws <MockException>(
                () => mock.Verify(foo => foo.Execute(""), Times.AtMostOnce()));

            Assert.Equal(MockException.ExceptionReason.VerificationFailed, mex.Reason);
        }
Example #8
0
        public void Create_ShouldCall_Create_From_Repository()
        {
            // устанавливаем параметр заглушки
            // в заглушке прописываем что в репозиторий прилетит HddMetric объект
            mock.Setup(repository => repository.Create(It.IsAny <HddMetric>())).Verifiable();

            // выполняем действие на контроллере
            var result = controller.Create(new MetricsAgent.Requests.HddMetricCreateRequest {
                Time = DateTimeOffset.FromUnixTimeSeconds(2), Value = 50
            });

            // проверяем заглушку на то, что пока работал контроллер
            // действительно вызвался метод Create репозитория с нужным типом объекта в параметре
            mock.Verify(repository => repository.Create(It.IsAny <HddMetric>()), Times.AtMostOnce());
        }
Example #9
0
        public void AddComment_Should_Use_IDomainObjectFactory_And_ICommentRepository()
        {
            var repository = SetupResolve <ICommentRepository>();
            var domFactory = SetupResolve <IDomainObjectFactory>();

            var now = SystemTime.Now();

            domFactory.Setup(f => f.CreateComment(_story.Object, "dummy content", now, It.IsAny <IUser>(), "127.0.0.1")).Returns(
                It.IsAny <IComment>()).Verifiable();

            _story.Object.AddComment("dummy content", now, new Mock <IUser>().Object, "127.0.0.1");

            domFactory.Verify();
            repository.Verify(r => r.Add(It.IsAny <IComment>()), Times.AtMostOnce());
        }
Example #10
0
        public void AddVote_Should_Use_IDomainObjectFactory_And_IVoteRepository()
        {
            var repository = SetupResolve <IVoteRepository>();
            var domFactory = SetupResolve <IDomainObjectFactory>();

            var now = SystemTime.Now();

            domFactory.Setup(f => f.CreateStoryVote(_story.Object, now, It.IsAny <IUser>(), "127.0.0.1")).Returns(
                It.IsAny <IVote>()).Verifiable();

            _story.Object.AddVote(now, new Mock <IUser>().Object, "127.0.0.1");

            domFactory.Verify();
            repository.Verify(r => r.Add(It.IsAny <IVote>()), Times.AtMostOnce());
        }
Example #11
0
        public void InstantiateFrameworkProviderCachesResults()
        {
            var providerMock       = new Mock <IFrameworkProvider>();
            var serviceLocatorMock = new Mock <IServiceLocator>();

            serviceLocatorMock.Setup(sl => sl.GetInstance <IFrameworkProvider>()).Returns(providerMock.Object);

            var factory = new Factory(serviceLocatorMock.Object);
            var first   = factory.InstantiateFrameworkProvider();
            var second  = factory.InstantiateFrameworkProvider();

            Assert.Equal(providerMock.Object, first);
            Assert.Equal(providerMock.Object, second);
            serviceLocatorMock.Verify(sl => sl.GetInstance <IFrameworkProvider>(), Times.AtMostOnce());
        }
        public void RejectedWithZeroTotal()
        {
            GivenSalesOrderAndCardInfo();
            moqCardValidator.Setup(m => m.Validate(It.IsAny <CardInfo>())).Returns(true);
            moqMerchantServicesAuthorizer.Setup(m => m.Authorize(It.IsAny <decimal>(), It.IsAny <CardInfo>())).Returns((string)null);

            salesOrder.SalesOrderItems.Clear();
            salesOrder.Total = 0;

            string authorizationCode = salesOrderManager.CompletePurchase(salesOrder, cardInfo);

            moqCardValidator.Verify(m => m.Validate(cardInfo), Times.AtMostOnce());
            moqSalesOrdersSet.Verify(m => m.Update(salesOrder), Times.Never());
            Assert.Null(authorizationCode);
        }
        public void ApplyModel_should_run_targeted_model_conventions()
        {
            var model                    = new EdmModel().Initialize();
            var entityType               = model.AddEntityType("E");
            var mockConvention           = new Mock <IEdmConvention <EntityType> >();
            var conventionsConfiguration = new ConventionsConfiguration(
                new IConvention[]
            {
                mockConvention.Object
            });

            conventionsConfiguration.ApplyModel(model);

            mockConvention.Verify(c => c.Apply(entityType, model), Times.AtMostOnce());
        }
Example #14
0
        public void GetAllAgentsCheckRequestCreate()
        {
            //Arrange
            var mockLogger = new Mock <ILogger <AgentsController> >();
            var mock       = new Mock <IAgentsRepository>();

            mock.Setup(a => a.GetAll()).Returns(new List <AgentModel>()).Verifiable();
            var controller = new AgentsController(mock.Object, mockLogger.Object);
            //Act
            var result = controller.GetAllAgents();

            //Assert
            mock.Verify(repository => repository.GetAll(), Times.AtMostOnce());
            mockLogger.Verify();
        }
Example #15
0
        public void DeleteAllOnSubmit_Should_Call_DeleteOnSubmit()
        {
            var stories = new List <Story> {
                new Story(), new Story(), new Story(), new Story()
            };

            _database.Object.InsertAllOnSubmit(stories);

            _database.Object.DeleteAllOnSubmit(stories.AsQueryable());
            foreach (var story in stories)
            {
                Story entity = story;
                _database.Verify(e => e.DeleteOnSubmit(entity), Times.AtMostOnce());
            }
        }
        public async Task SubmitOrder_Should_ReturnSuccess_WithValidOrder()
        {
            //Arrange
            options.Setup(x => x.Value).Returns(apiSettings);
            HttpClient httpClient = new HttpClient(httpMessageHandlerMock.Object);

            orderService = new OrderService(httpClient, options.Object, logger.Object);
            httpMessageHandlerMock.Protected().Setup <Task <HttpResponseMessage> >(
                "SendAsync",
                ItExpr.IsAny <HttpRequestMessage>(),
                ItExpr.IsAny <CancellationToken>()
                )
            .ReturnsAsync(new HttpResponseMessage()
            {
                StatusCode = HttpStatusCode.OK,
                Content    = new StringContent(JsonConvert.SerializeObject("Order Submitted"), Encoding.UTF8, "application/json")
            })
            .Verifiable();

            var order = new Order
            {
                LineItems = new List <OrderItem> {
                    new OrderItem {
                        ProductId = "123", Quantity = 1
                    }
                },
                CustomerEmail = "*****@*****.**",
                CustomerName  = "testName"
            };

            //Act
            var result = await orderService.SubmitOrder(order);

            // Assert
            Assert.IsNotNull(result);
            Assert.AreEqual("\"Order Submitted\"", result);
            httpMessageHandlerMock.Protected().Verify(
                "SendAsync",
                Times.AtMostOnce(), // verify number of times SendAsync is called
                ItExpr.Is <HttpRequestMessage>(req =>
                                               req.Method == HttpMethod.Post && // verify the HttpMethod for request is GET
                                               req.RequestUri.ToString() == apiSettings.BaseUrl && // verify the RequestUri is as expected
                                               req.Headers.GetValues("Accept").FirstOrDefault() == "application/json" && //Verify Accept header
                                               req.Headers.GetValues("tracking-id").FirstOrDefault() != null //Verify tracking-id header is added
                                               ),
                ItExpr.IsAny <CancellationToken>()
                );
        }
Example #17
0
        public void ReuseExistingLogger()
        {
            var logger      = new NullLogger();
            var locatorMock = new Mock <IServiceLocator>();

            locatorMock.Setup(l => l.GetInstance <ILogger>()).Returns(logger);

            var factory = new Factory(locatorMock.Object);

            var first  = factory.InstantiateLogger();
            var second = factory.InstantiateLogger();

            Assert.Equal(logger, first);
            Assert.Equal(logger, second);
            locatorMock.Verify(l => l.GetInstance <ILogger>(), Times.AtMostOnce());
        }
Example #18
0
        //
        // You can use the following additional attributes as you write your tests:
        //
        // Use ClassInitialize to run code before running the first test in the class
        // [ClassInitialize()]
        // public static void MyClassInitialize(TestContext testContext) { }
        //
        // Use ClassCleanup to run code after all tests in a class have run
        // [ClassCleanup()]
        // public static void MyClassCleanup() { }
        //
        // Use TestInitialize to run code before running each test
        //[TestInitialize()]
        //public void MyTestInitialize() { }
        //
        // Use TestCleanup to run code after each test has run
        // [TestCleanup()]
        // public void MyTestCleanup() { }
        //
        #endregion


        /// <summary>
        /// Test that SaveMessage makes the necessary save method to the backend repository
        /// </summary>
        /// <returns></returns>
        //[TestMethod]
        public async Task V1_SaveMessage_SavesData_ToRepository()
        {
            //arrange
            var mockRepository = new Mock <IHelloWorldRepository>();

            mockRepository.Setup(m => m.SaveMessageAsync(It.IsAny <string>())).Returns(Task.FromResult(false));
            IHelloWorldDbApi api = new HelloWorldDbApiV1(mockRepository.Object);

            string msg = "Hello World";

            //act
            await api.SaveMessageAsync(msg);

            //assert a call to the repository was made.
            mockRepository.Verify(mock => mock.SaveMessageAsync(msg), Times.AtMostOnce());
        }
Example #19
0
        public void Create_ShouldCall_Create_From_Repository()
        {
            // устанавливаем параметр заглушки
            // в заглушке прописываем что в репозиторий прилетит Metric объект
            _mock.Setup(repository =>
                        repository.Create(It.IsAny <CpuMetric>())).Verifiable();
            // выполняем действие на контроллере
            var result = _controller.Create(new
                                            MetricsAgent.Requests.CpuMetricCreateRequest
            {
                Time  = DateTimeOffset.FromUnixTimeSeconds(1),
                Value = 50
            });

            _mock.Verify(repository => repository.Create(It.IsAny <CpuMetric>()), Times.AtMostOnce());
        }
Example #20
0
        public void ShouldOnlyRunPotentiallyExpensiveChecksOnceIfSuccessful()
        {
            // When the waiter waits for a check which is already true
            var checkProvider = new Mock <IProvideChecks>();

            checkProvider.Setup(cp => cp.Check()).Returns(true);

            new Waiter().WaitFor(new Panel(AutomationElement.RootElement, "Desktop"),
                                 (src, e) => checkProvider.Object.Check(),
                                 new TimeSpan(0, 0, 5),
                                 (ex) => Assert.Fail("Could not handle guaranteed event"),
                                 new List <AutomationEventWrapper>());

            // Then it should only have run once
            checkProvider.Verify(cp => cp.Check(), Times.AtMostOnce());
        }
Example #21
0
        public void ThrowsIfVerifyVoidAtMostOnceAndMoreThanOneCall()
        {
            var mock = new Mock <IFoo>();

            mock.Object.Submit();

            mock.Verify(foo => foo.Submit(), Times.AtMostOnce());

            mock.Object.Submit();

            var mex = Assert.Throws <MockException>(() =>
                                                    mock.Verify(foo => foo.Submit(), Times.AtMostOnce()));

            Assert.Equal(MockException.ExceptionReason.VerificationFailed, mex.Reason);
            Assert.Contains("Expected invocation on the mock at most once, but was 2 times: foo => foo.Submit()", mex.Message);
        }
Example #22
0
        public void ImportSameCoursesTwice()
        {
            var course  = GetCourses(1).First();
            var result1 = subject.SaveCourses(new List <Course> {
                course
            }).Result;

            AssertOkay(result1);
            locationRequesterMock.Verify(x => x.RequestLocations(), Times.AtMostOnce());


            var course2 = GetCourses(1).First();
            var result2 = subject.SaveCourses(new List <Course> {
                course2
            }).Result;

            AssertOkay(result2);
            locationRequesterMock.Verify(x => x.RequestLocations(), Times.Exactly(2));


            var resultingCourses   = context.GetCoursesWithProviderSubjectsRouteAndCampuses().ToList();
            var resultingProviders = context.Providers.ToList();

            resultingCourses.Count().Should().Be(1);
            var savedCourse = resultingCourses.First();

            savedCourse.Campuses.Count().Should().Be(course.Campuses.Count());
            savedCourse.DescriptionSections.Count().Should().Be(course.DescriptionSections.Count());
            resultingCourses.SelectMany(x => x.DescriptionSections).Count().Should().Be(course.DescriptionSections.Count());

            // deduplicated
            var courses = new List <Course> {
                course, course2
            };

            resultingProviders.Count.Should().Be(1);
            context.Routes.Count().Should().Be(1);
            context.Subjects.Count().Should().Be(1);
            var expectedLocations = GetExpectedLocations(courses);

            context.Locations.Count().Should().Be(expectedLocations.Count());
            context.Campuses.Count().Should().Be(4); //definately right

            // non-deduplicated
            context.Contacts.Count().Should().Be(2); //probably wrong
            context.CourseSubjects.Count().Should().Be(1);
        }
        public void CanCreateOrder()
        {
            // var db = new Mock<ShoppingDb>();

            var customerRepository = new Mock <IRepository <Customer> >();
            var orderRepository    = new Mock <IRepository <Order> >();
            var productRepository  = new Mock <IRepository <Product> >();

            // var orderController = new OrderController(orderRepository.Object,
            //                                          productRepository.Object);


            var unitOfWork = new Mock <IUnitOfWork>();

            unitOfWork.Setup(uow => uow.CustomerRepository).Returns(() => customerRepository.Object);
            unitOfWork.Setup(uow => uow.OrderRepository).Returns(() => orderRepository.Object);
            unitOfWork.Setup(uow => uow.ProductRepository).Returns(() => productRepository.Object);

            var orderController = new OrderController(unitOfWork.Object);

            var createOrder = new CreateOrderModel
            {
                Customer = new CustomerModel
                {
                    Name            = "Tom Randles",
                    ShippingAddress = "Knocknacarra, Galway",
                    City            = "Galway",
                    Country         = "Ireland"
                },
                LineItems = new[]
                {
                    new LineItemModel {
                        ProductId = Guid.NewGuid(), Quantity = 4
                    },
                    new LineItemModel {
                        ProductId = Guid.NewGuid(), Quantity = 2
                    }
                }
            };

            // Create order
            orderController.Create(createOrder);

            // Verify that the order repository Add function was called once.
            orderRepository.Verify(repository => repository.Add(It.IsAny <Order>()),
                                   Times.AtMostOnce());
        }
        public void AddCommentToEncounterEncountersController()
        {
            var encounterServices        = new Mock <IEncounterSimpleServices>();
            var encounterQueryServices   = new Mock <IEncounterQueryServices>();
            var fixtureGeneratorServices = new Mock <IFixtureServices>();

            ILoginServices loginServices = new LoginServicesMock(santiago);

            var httpContext = new DefaultHttpContext();

            httpContext.Request.Headers["Authorization"] = "";

            var controllerContext = new ControllerContext()
            {
                HttpContext = httpContext,
            };

            EncounterDTO encounter = new EncounterDTO()
            {
                Id = IntToGuid(4), SportName = "Futbol", TeamIds = new List <string>()
                {
                    "Peñarol", "Nacional"
                }
            };
            IEnumerable <EncounterDTO> encounters = new List <EncounterDTO>()
            {
                encounter
            };

            encounterServices.Setup(e => e.GetAllEncounters()).Returns(encounters);

            var controller = new EncountersController(loginServices, encounterServices.Object, new LoggerStub(), encounterQueryServices.Object, fixtureGeneratorServices.Object, teamServices.Object)
            {
                ControllerContext = controllerContext,
            };

            var comment = new CommentModelIn()
            {
                Message = "This is a test comment in a mock!"
            };
            var obtainedResult = controller.AddEncounterComment(4 + "", comment) as OkResult;

            encounterServices.Verify(m => m.GetAllEncounters(), Times.AtMostOnce());

            Assert.IsNotNull(obtainedResult);
            Assert.AreEqual(200, obtainedResult.StatusCode);
        }
Example #25
0
        public void ThrowsIfVerifyVoidAtMostOnceAndMoreThanOneCall()
        {
            var mock = new Mock <IFoo>();

            mock.Object.Submit();

            mock.Verify(foo => foo.Submit(), Times.AtMostOnce());

            mock.Object.Submit();

            var mex = AssertHelper.Throws <MockException>(() =>
                                                          mock.Verify(foo => foo.Submit(), Times.AtMostOnce()));

            Assert.AreEqual(MockException.ExceptionReason.VerificationFailed, mex.Reason);
            Assert.IsTrue(mex.Message.StartsWith(
                              "\r\nExpected invocation on the mock at most once, but was 2 times: foo => foo.Submit()"));
        }
Example #26
0
        public void WhenCallingStartAndMessageAddedThenImmediatelyStopShouldNotCallPostOnHttpClient()
        {
            var message = this.CreateMessage();

            this.ForwardService.Start();
            Thread.Sleep(50);

            this.PersistentStore.Add(message);
            this.ForwardService.Stop();
            Thread.Sleep(200);

            this.PersistentStore.Add(this.CreateMessage());
            Thread.Sleep(200);

            Assert.NotNull(this.PersistentStore.Get());
            this.HttpClient.Verify(c => c.Post(It.IsAny <IMessage>()), Times.AtMostOnce());
        }
        public void GetCardsPassed()
        {
            // Arrange
            var mock      = new Mock <IBankRepository>();
            var mockCards = new FakeDataGenerator(_businessLogicService).GenerateFakeCards();

            mock.Setup(r => r.GetCards()).Returns(mockCards);

            var controller = new CardsController(mock.Object, _cardService, _businessLogicService);

            // Test
            var cards = controller.Get();

            // Assert
            mock.Verify(r => r.GetCards(), Times.AtMostOnce());
            Assert.Equal(3, cards.Count());
        }
        public void Should_Create_First_Generation_When_Initialising_World()
        {
            // Arrange
            var presenter        = new Mock <IDisplayPresenter>();
            var quitManager      = new Mock <IQuitManager>();
            var saveStateManager = new Mock <ISaveStateManager>();
            var worldGenerator   = new Mock <IWorldGenerator>();

            worldGenerator.Setup(o => o.CreateFirstGeneration(It.IsAny <string>())).Returns(It.IsAny <World>());
            var controller = new GameController(presenter.Object, quitManager.Object, saveStateManager.Object, worldGenerator.Object);

            // Act
            var world = controller.InitialiseFirstWorld(new[] { "TestFiles/ValidInitialState.json" });

            // Assert
            worldGenerator.Verify(o => o.CreateFirstGeneration(It.IsAny <string>()), Times.AtMostOnce());
        }
Example #29
0
        public void Bruker_Er_I_DB_OK()
        {
            var _mock  = new Mock <InterfaceDbTBruker>();
            var Loggin = new LogInn()
            {
                Brukernavn = "*****@*****.**",
                Passord    = "Password123",
            };

            _mock.Setup(x => x.BrukerIdb(Loggin)).Returns(true);
            _mock.Verify(framework => framework.BrukerIdb(Loggin), Times.AtMostOnce());

            InterfaceDbTBruker lovable = _mock.Object;
            var actual = lovable.BrukerIdb(Loggin);

            Assert.AreEqual(true, actual);
        }
Example #30
0
        public void Play_2_Sides_Winner_Determined()
        {
            //Arrange
            target = new PlayTournament(playMatches);
            var winner = new Mock <ISide>();

            playMatch.Setup <ISide>(m => m.Play()).Returns(winner.Object);

            //Act
            var result = target.Play();

            //Assert
            Assert.IsNotNull(result);
            Assert.AreEqual(winner.Object, result);
            playMatch.Verify(m => m.Play(), Times.AtMostOnce());
            Assert.AreEqual(1, target.GetMatchScores().Count());
        }