public void AssemblyAnalisysTest()
        {
            Assembly assembly = Assembly.Load("Karma.Core.AssemblyAnalyzerSample");

            MockRepository repository = new MockRepository();

            IClassAnalyzer classAnalyzer = repository.StrictMock<IClassAnalyzer>();
            Expect.Call(classAnalyzer.Analyze(null))
                .IgnoreArguments()
                .Return(new ClassMetadata(typeof(User)))
                .Repeat.Twice();

            repository.ReplayAll();

            AssemblyAnalyzer analyzer = new AssemblyAnalyzer();
            analyzer.ClassAnalyzer = classAnalyzer;

            AssemblyMetadata metadata = analyzer.Analyze(assembly);

            Assert.That(metadata, Is.Not.Null);
            Assert.That(metadata.Attributes, Is.Not.Null);
            Assert.That(metadata.Attributes, Is.Not.Empty);
            Assert.That(metadata.Attributes.Count, Is.EqualTo(1));
            Assert.That(metadata.Classes, Is.Not.Null);
            Assert.That(metadata.Classes, Is.Not.Empty);
            Assert.That(metadata.Classes.Count, Is.EqualTo(2));

            repository.VerifyAll();
        }
        public void OnViewLoadedSetsCategorieIntheView()
        {
            // Mock the View
            MockRepository mocks = new MockRepository();
            //Arrange
            var service = mocks.DynamicMock<ICategorieService>();

            //Act
            var controller = mocks.DynamicMock<ICategorieController>();

            // Create Presenter With Mock View and Dummy BlogService
            CategorieService serviceActual = new MockCategorieService();
            var controllerActual = new CategorieController(serviceActual,null,null);
            var presenter = new CategorieenPresenter(controllerActual);
            var cat = new BeheerContextEntity { DataKeyValue = "added" };
            IList<BeheerContextEntity> list= new List<BeheerContextEntity>();
            list.Add(cat);
            //controller.AddBusinessEntity(cat);

            // Set Expectations  
            controller.Expect(action=>action.AddBusinessEntity(cat));
            //presenter.Expect(action => action.OnViewLoaded());
            
            
            // Tell Rhino Mocks We're Done Setting Expectations
            mocks.ReplayAll();
            presenter.OnViewLoaded();
            
            mocks.VerifyAll();


        }
		public void Creates_database()
		{
			var settings = new ConnectionSettings("server", "db", true, null, null);
            var taskAttributes = new TaskAttributes(settings, "c:\\scripts");
            taskAttributes.RequestedDatabaseAction= RequestedDatabaseAction.Create;
			var mocks = new MockRepository();
            var queryExecutor = mocks.StrictMock<IQueryExecutor>();
            var executor = mocks.StrictMock<IScriptFolderExecutor>();
            var taskObserver = mocks.StrictMock<ITaskObserver>();
			
			using (mocks.Record())
			{
				queryExecutor.ExecuteNonQuery(settings, "create database [db]");
                taskObserver.Log(string.Format("Run scripts in Create folder."));
				executor.ExecuteScriptsInFolder(taskAttributes, "Create", taskObserver);
			}

			using (mocks.Playback())
			{
				IDatabaseActionExecutor creator = new DatabaseCreator(queryExecutor, executor);
				creator.Execute(taskAttributes, taskObserver);
			}

			mocks.VerifyAll();
		}
        public void GetById_Calls_GigDAO_Method_GetById_Once_And_Returns_A_Gig()
        {
            MockRepository mocks = new MockRepository();

            Guid gigId = Guid.NewGuid();
            Gig gig = new Gig();
            gig.ID = gigId;

            IGigDAO gigDAO = mocks.DynamicMock<IGigDAO>();
            GigManager gigManager = new GigManager();
            gigManager.GigDAO = gigDAO;

            Expect.Call(gigDAO.GetById(gigId))
               .Constraints(Is.Equal(gigId))
               .Repeat.Once()
               .Return(gig);

            mocks.ReplayAll();

            Gig result = gigManager.GetByID(gigId);

            mocks.VerifyAll();

            Assert.AreEqual(gig.ID, result.ID);
        }
        public static void GetMatchNonMatchTest(
			string headerName, 
			string[] values, 
			bool existsInStore,
			bool expectReturnNull,
			HttpStatusCode expectedStatus = HttpStatusCode.Unused)
        {
            // setup
            var mocks = new MockRepository();
            var entityTagStore = mocks.StrictMock<IEntityTagStore>();
            var entityTagHandler = new CachingHandler(entityTagStore);
            var request = new HttpRequestMessage(HttpMethod.Get, TestUrl);
            request.Headers.Add(headerName, values);
            TimedEntityTagHeaderValue entityTagHeaderValue = new TimedEntityTagHeaderValue("\"12345678\"");

            if(values.Length>0) // if
                entityTagStore.Expect(x => x.TryGetValue(Arg<CacheKey>.Matches(etg => etg.ResourceUri == entityTagHandler.UriTrimmer(new Uri(TestUrl))),
                    out Arg<TimedEntityTagHeaderValue>.Out(entityTagHeaderValue).Dummy)).Return(existsInStore);

            mocks.ReplayAll();

            // run
            var matchNoneMatch = entityTagHandler.GetIfMatchNoneMatch();
            // verify
            Task<HttpResponseMessage> resultTask = matchNoneMatch(request);
            Assert.That(expectReturnNull ^ resultTask != null, "result was not as expected");
            if(resultTask!=null && expectedStatus != HttpStatusCode.Unused)
            {
                Assert.AreEqual(expectedStatus, resultTask.Result.StatusCode, "Status code");
            }
            mocks.VerifyAll();
        }
        public void ShouldBeAbleToAddNewOrder()
        {
            // arrange
            var mock = new MockRepository();
            var repository = mock.DynamicMock<IOrderRepository>();
            const string IdentityToken = "*****@*****.**";
            const string RetailerUrl = "amazon.com";
            Expect.Call(repository.AddOrder(IdentityToken, new Order { Retailer = new Retailer(RetailerUrl) }))
                .Return(new Order(OrderStatus.New) { Retailer = new Retailer(RetailerUrl), CreatedDate = DateTime.UtcNow });
            var service = new OrderService(repository, new FakeEmailService(), this.logger);
            var request = new AddOrderRequest
                {
                    IdentityToken = IdentityToken,
                    RetailerUrl = RetailerUrl,
                    CreatedDate = DateTime.UtcNow
                };

            // act
            mock.ReplayAll();
            var actual = service.AddOrder(request);
            mock.VerifyAll();

            // assert
            Assert.That(actual, Is.Not.Null);
            Assert.That(actual.CreatedDate, Is.EqualTo(request.CreatedDate).Within(1).Minutes);
            Assert.That(actual.RetailerUrl, Is.EqualTo(request.RetailerUrl));
        }
        public void ShouldIgnoreArgumentsOnGenericCallWhenTypeIsStruct()
        {
            // setup
            MockRepository mocks = new MockRepository();
            ISomeService m_SomeServiceMock = mocks.StrictMock<ISomeService>();
            SomeClient sut = new SomeClient(m_SomeServiceMock);

            using (mocks.Ordered())
            {
                Expect.Call(delegate
                {
                    m_SomeServiceMock.DoSomething<string>(null, null);
                });
                LastCall.IgnoreArguments();

                Expect.Call(delegate
                {
                    m_SomeServiceMock.DoSomething<DateTime>(null, default(DateTime));  // can't use null here, because it's a value type!
                });
                LastCall.IgnoreArguments();

            }
            mocks.ReplayAll();

            // test
            sut.DoSomething();

            // verification
            mocks.VerifyAll();

            // cleanup
            m_SomeServiceMock = null;
            sut = null;
        }
        public void Updates_database()
        {
            var settings = new ConnectionSettings("server", "db", true, null, null);
            var taskAttributes = new TaskAttributes(settings, "c:\\scripts");
            taskAttributes.RequestedDatabaseAction = RequestedDatabaseAction.Update;
            var mocks = new MockRepository();
            var scriptfolderexecutor = mocks.StrictMock<IScriptFolderExecutor>();
            var queryexecutor = mocks.StrictMock<IQueryExecutor>();
            queryexecutor.Stub(x => x.CheckDatabaseExists(taskAttributes.ConnectionSettings)).Return(true);

            var taskObserver = mocks.StrictMock<ITaskObserver>();
            using (mocks.Record())
            {
                taskObserver.Log(string.Format("Run scripts in Update folder."));
                scriptfolderexecutor.ExecuteScriptsInFolder(taskAttributes, "Update", taskObserver);

                taskObserver.Log(string.Format("Run scripts in Everytime folder."));
                scriptfolderexecutor.ExecuteChangedScriptsInFolder(taskAttributes, "Everytime", taskObserver);

                taskObserver.Log(string.Format("Run scripts in RunAlways folder."));
                scriptfolderexecutor.ExecuteRunAlwaysScriptsInFolder(taskAttributes, "RunAlways", taskObserver);
            }

            using (mocks.Playback())
            {
                IDatabaseActionExecutor updater = new DatabaseUpdater(scriptfolderexecutor, queryexecutor);
                updater.Execute(taskAttributes, taskObserver);
            }

            mocks.VerifyAll();
        }
Beispiel #9
0
        public void BidirectionalConverter_Should_Convert_All_Items()
        {
            var mocks = new MockRepository();
            var converter1 = mocks.StrictMock<IBidirectionalConverter<int, string>>();

            Expect.Call(converter1.Convert(5)).Return("5");
            Expect.Call(converter1.Convert(3)).Return("3");
            Expect.Call(converter1.Convert(7)).Return("7");

            var converter2 = mocks.StrictMock<IBidirectionalConverter<string, int>>();

            Expect.Call(converter2.Convert("5")).Return(5);
            Expect.Call(converter2.Convert("3")).Return(3);
            Expect.Call(converter2.Convert("7")).Return(7);

            mocks.ReplayAll();

            // Convert one way
            IList<int> input1 = new List<int> { 5, 3, 7 };
            var output1 = converter1.ConvertAll(input1);

            Assert.IsTrue(output1.Contains("5"));
            Assert.IsTrue(output1.Contains("3"));
            Assert.IsTrue(output1.Contains("7"));

            // Convert the other way
            IList<string> input2 = new List<string> { "5", "3", "7" };
            var output2 = converter2.ConvertAll(input2);

            Assert.IsTrue(output2.Contains(5));
            Assert.IsTrue(output2.Contains(3));
            Assert.IsTrue(output2.Contains(7));

            mocks.VerifyAll();
        }
		public void Certifies_deployment()
		{
			var deployment = new Deployment();

			var mocks = new MockRepository();
			var clock = mocks.CreateMock<ISystemClock>();
			var securityContext = mocks.CreateMock<ISecurityContext>();
			var repository = mocks.CreateMock<IDeploymentRepository>();

			using (mocks.Record())
			{
				Expect.Call(clock.GetCurrentDateTime()).Return(new DateTime(2007, 4, 15));
				Expect.Call(securityContext.GetCurrentUsername()).Return("khurwitz");
				repository.Save(deployment);
			}

			using (mocks.Playback())
			{
				IVersionCertifier certifier = new VersionCertifier(clock, securityContext, repository);
				certifier.Certify(deployment);
				
				Assert.That(deployment.CertifiedBy, Is.EqualTo("khurwitz"));
				Assert.That(deployment.CertifiedOn, Is.EqualTo(new DateTime(2007, 4, 15)));
			}

			mocks.VerifyAll();
		}
Beispiel #11
0
        public void Search()
        {
            // Basic integration test: search algorithms are already extensively tested with InMemoryIndexBase

            MockRepository mocks = new MockRepository();

            IIndexConnector conn = mocks.StrictMock<IIndexConnector>();
            ScrewTurn.Wiki.SearchEngine.IWordFetcher fetcher = mocks.StrictMock<ScrewTurn.Wiki.SearchEngine.IWordFetcher>();

            ScrewTurn.Wiki.SearchEngine.Word dummy = null;
            Expect.Call(fetcher.TryGetWord("test", out dummy)).Return(false);
            Expect.Call(fetcher.TryGetWord("query", out dummy)).Return(false);
            fetcher.Dispose();
            LastCall.On(fetcher);

            Expect.Call(conn.GetWordFetcher()).Return(fetcher);

            mocks.ReplayAll();

            SqlIndex index = new SqlIndex(conn);

            Assert.AreEqual(0, index.Search(new ScrewTurn.Wiki.SearchEngine.SearchParameters("test query")).Count, "Wrong search result count");

            mocks.VerifyAll();
        }
		public void Should_not_fail_if_datebase_does_not_exist()
		{
			var settings = new ConnectionSettings("server", "db", true, null, null);
            var taskAttributes = new TaskAttributes(settings, null);

			var mocks = new MockRepository();
			var connectionDropper = mocks.DynamicMock<IDatabaseConnectionDropper>();
			var taskObserver = mocks.CreateMock<ITaskObserver>();
			var queryExecutor = mocks.CreateMock<IQueryExecutor>();

			using (mocks.Record())
			{
                Expect.Call(() => queryExecutor.ExecuteNonQuery(settings, "ALTER DATABASE [db] SET SINGLE_USER WITH ROLLBACK IMMEDIATE drop database [db]", false))
					.Throw(new Exception("foo message"));
				Expect.Call(() => taskObserver.Log("Database 'db' could not be dropped."));
			}

			using (mocks.Playback())
			{
				IDatabaseActionExecutor dropper = new DatabaseDropper(connectionDropper, queryExecutor);
                dropper.Execute(taskAttributes, taskObserver);
			}

			mocks.VerifyAll();
		}
        public void GigController_Should_Contain_Index_Method_Which_Accepts_GigID_And_Returns_A_Gig()
        {
            MockRepository mocks = new MockRepository();

            Guid gigId = Guid.NewGuid();
            Gig gig = new Gig();
            gig.ID = gigId;

            //Mock the GigManager
            IGigManager gigManager = mocks.DynamicMock<IGigManager>();
            GigController gigController = new GigController();
            gigController.GigManager = gigManager;

            Expect.Call(gigManager.GetByID(gigId))
                .Constraints(Is.Equal(gigId))
                .Repeat.Once()
                .Return(gig);

            mocks.ReplayAll();

            ViewResult result = (ViewResult)gigController.Index(gigId);
            Gig returnedData = (Gig)(result.ViewData.Model);

            mocks.VerifyAll();

            Assert.IsNotNull(returnedData);
            Assert.AreEqual(gig.ID, returnedData.ID);
        }
		public void Drops_database()
		{
			var settings = new ConnectionSettings("server", "db", true, null, null);
            var taskAttributes = new TaskAttributes(settings, null);

			var mocks = new MockRepository();
			var connectionDropper = mocks.CreateMock<IDatabaseConnectionDropper>();
			var taskObserver = mocks.CreateMock<ITaskObserver>();
			var queryExecutor = mocks.CreateMock<IQueryExecutor>();
            
			using (mocks.Record())
			{
				connectionDropper.Drop(settings, taskObserver);
                
                queryExecutor.ExecuteNonQuery(settings, "ALTER DATABASE [db] SET SINGLE_USER WITH ROLLBACK IMMEDIATE drop database [db]", false);
			    
			}

			using (mocks.Playback())
			{
				IDatabaseActionExecutor dropper = new DatabaseDropper(connectionDropper, queryExecutor);
				dropper.Execute(taskAttributes, taskObserver);
			}

			mocks.VerifyAll();
		}
Beispiel #15
0
        public void CanCreateNewSite()
        {
            Site site = DomainTestHelper.GetTestSite();

             Theme theme = MockRepository.GenerateStub<Theme>();
             theme.BasePath = "~/themes/default";
             theme.Name = "default";
             site.Theme = theme;

             MockRepository mocks = new MockRepository();
             sessionFactory = MockRepository.GenerateMock<Arashi.Core.NHibernate.ISessionFactory>();
             session = MockRepository.GenerateMock<ISession>();
             Site createdSite;

             using (mocks.Record())
             {
            sessionFactory.Expect(x => x.GetSession()).Return(session /*MockRepository.GenerateStub<ISession>()*/);
            session.Expect(x => x.BeginTransaction()).Return(MockRepository.GenerateStub <ITransaction>());
             }
             using (mocks.Playback())
             {
            ISiteService siteService = new SiteService( sessionFactory, // this.AutoMockingContainer().Resolve<Arashi.Core.NHibernate.ISessionFactory>(),
                                                         this.AutoMockingContainer().Resolve<ILog>(),
                                                         this.AutoMockingContainer().Resolve<IUserService>(),
                                                         this.AutoMockingContainer().Resolve<IFileService>());

            createdSite = siteService.CreateNewSite("Test", "test", "*****@*****.**", "localhost", theme);
             }

             mocks.VerifyAll();

             createdSite.Should().Not.Be.Null();
             createdSite.Name.Should().Be.EqualTo(site.Name);
             createdSite.Hosts.Count.Should().Be.GreaterThanOrEqualTo(1);
             createdSite.Hosts[0].Should().Not.Be.Null();
             createdSite.Theme.Should().Be.EqualTo(theme);

             //NHibernate.ISession session = mocks.StrictMock<NHibernate.ISession>();
             //NHibernate.ITransaction transaction = mocks.Stub<NHibernate.ITransaction>();
             //Student expected = new Student();
             //Student actual;
             //using (mocks.Record())
             //{
             //   Rhino.Mocks.Expect.Call(session.Transaction)
             //       .Return(transaction)
             //       .Repeat.Any();
             //   Rhino.Mocks.Expect.Call(transaction.IsActive)
             //       .Return(true);
             //   Rhino.Mocks.Expect.Call(session.Get<Student>(Guid.Empty))
             //       .Return(expected);
             //}
             //using (mocks.Playback())
             //{
             //   IReadStudent StudentDao = new StudentDAOImpl(session);
             //   actual = StudentDao.GetById(Guid.Empty);
             //}
             //mocks.VerifyAll();
             //Assert.IsNotNull(actual);
             //Assert.AreSame(expected, actual);
        }
		public void Executes_all_the_scripts_within_a_folder()
		{
			var settings = new ConnectionSettings("server", "db", true, null, null);
            var sqlFiles = new[] { "c:\\scripts\\Update\\001.sql", "c:\\scripts\\Update\\002_data_.sql", "c:\\scripts\\Update\\003.sql" };
            var taskAttributes = new TaskAttributes(settings, "c:\\scripts")
                                     {
                                         RequestedDatabaseAction = RequestedDatabaseAction.Update,
                                     };

			var mocks = new MockRepository();
            var initializer = mocks.StrictMock<ISchemaInitializer>();
            var fileLocator = mocks.StrictMock<ISqlFileLocator>();
            var executor = mocks.StrictMock<IChangeScriptExecutor>();
            var testdataexecutor = mocks.StrictMock<ITestDataScriptExecutor>();
            var versioner = mocks.StrictMock<IDatabaseVersioner>();
            var taskObserver = mocks.StrictMock<ITaskObserver>();

			using (mocks.Record())
			{
				initializer.EnsureSchemaCreated(settings);
				Expect.Call(fileLocator.GetSqlFilenames("c:\\scripts", "Update")).Return(sqlFiles);
				executor.Execute("c:\\scripts\\Update\\001.sql", settings, taskObserver);
				executor.Execute("c:\\scripts\\Update\\002_data_.sql", settings, taskObserver);
				executor.Execute("c:\\scripts\\Update\\003.sql", settings, taskObserver);
				versioner.VersionDatabase(settings, taskObserver);
			}

			using (mocks.Playback())
			{
                IScriptFolderExecutor folderExecutor = new ScriptFolderExecutor(initializer, fileLocator, executor, testdataexecutor, versioner);
				folderExecutor.ExecuteScriptsInFolder(taskAttributes, "Update", taskObserver);
			}

			mocks.VerifyAll();
		}
Beispiel #17
0
        public void Simple()
        {
            var list = GetTestList();

                var mockRepository = new MockRepository();
                var trackingList = mockRepository.StrictMock<IList<int>>();

                // All items should be visited...
                trackingList.Add(1);
                trackingList.Add(2);
                trackingList.Add(3);
                trackingList.Add(8);
                trackingList.Add(5);

                mockRepository.ReplayAll();

                var generalVisitor = new GeneralVisitor<int>(
                    delegate (int value) {
                                             trackingList.Add(value);
                                             return false;
                    }
                    );

                list.AcceptVisitor(generalVisitor);

                mockRepository.VerifyAll();
        }
        public void Do3Classic()
        {
            var mockRepository = new MockRepository();
            var view = mockRepository.StrictMock<IButtonView>();
            var model = mockRepository.StrictMock<IToggleModel>();

            model.VisibilityStateChanged += null;
            IEventRaiser visibilityChanged = LastCall.GetEventRaiser();

            view.Clicked += null;
            IEventRaiser clicked = LastCall.GetEventRaiser();

            var presenter = new ButtonPresenter(model);
            presenter.ConnectView(view);

            mockRepository.BackToRecordAll();
            //mockRepository.Playback();

            Expect.Call(model.ToggleVisibility);
            Expect.Call(() => model.VisibilityStateChanged += null).IgnoreArguments();
            Expect.Call(() => view.SetCheckedState(CheckedState.Checked));

            mockRepository.ReplayAll();

            clicked.Raise();
            visibilityChanged.Raise(VisibilityState.Visible);

            mockRepository.VerifyAll();
        }
        public void PublishDomainEvents()
        {
            var e = new TestEvent();

            var mockRepository = new MockRepository();
            IEnumerable<object> handlers;

            using (mockRepository.Record())
            {
                var handler1 = mockRepository.StrictMock<IEventHandler<TestEvent>>();
                handler1.Expect(h => h.Handle(e)).Repeat.Once();

                var handler2 = mockRepository.StrictMock<IEventHandler<TestEvent>>();
                handler2.Expect(h => h.Handle(e)).Repeat.Once();

                handlers = new[] { handler1, handler2 };
            }

            MultiInstanceFactory multiInstanceFactory = t => handlers;

            var publisher = new DomainEventsPublisher(multiInstanceFactory);
            DomainEvents.Raise(e);

            using (mockRepository.Playback())
                publisher.Publish();

            mockRepository.VerifyAll();
        }
		public void SetPort_three_locations()
		{
			var expectedPort = 1234;
			var mockRepository = new MockRepository();

			// Arrange
			var fileManipulation = mockRepository.StrictMock<IFileManipulation>();
			var paths = mockRepository.StrictMock<IPaths>();

			var neo4JServerConfigSettings = mockRepository.StrictMock<INeo4jServerConfigSettings>();
			neo4JServerConfigSettings.Expect(n => n.Port).Return("org.neo4j.server.webserver.port");
			neo4JServerConfigSettings.Expect(n => n.WebAdminDataUri).Return("webadmindatauri");
			neo4JServerConfigSettings.Expect(n => n.WebAdminManagementUri).Return("webadminmanagementuri");

			var neo4JManager = new Neo4jManager(fileManipulation, null);

			paths.Expect(p => p.Neo4jServerConfigSettings).Return(neo4JServerConfigSettings);

			paths.Expect(p => p.Neo4jAdminDataUri).Return("Neo4jAdminDataUri");
			paths.Expect(p => p.Neo4jAdminManagementUri).Return("Neo4jAdminManagementUri");
			paths.Expect(p => p.Neo4jServerConfigPath).Return("Neo4jServerConfigPath");

			fileManipulation.Expect(fm => fm.ReplaceConfigLine(null, null)).IgnoreArguments();

			mockRepository.ReplayAll();

			// Act
			neo4JManager.SetServerPortAndUrlConfig(paths, expectedPort);

			// Assert
			mockRepository.VerifyAll();
		}
        public void Correctly_constructs_action_executors()
        {
            DatabaseAction[] actions = new DatabaseAction[] { DatabaseAction.Create, DatabaseAction.Update };

            MockRepository mocks = new MockRepository();
            IDatabaseActionResolver resolver = mocks.StrictMock<IDatabaseActionResolver>();
            IDataBaseActionLocator locator = mocks.StrictMock<IDataBaseActionLocator>();

            IDatabaseActionExecutor creator = mocks.StrictMock<IDatabaseActionExecutor>();
            IDatabaseActionExecutor updater = mocks.StrictMock<IDatabaseActionExecutor>();

            using (mocks.Record())
            {
                Expect.Call(resolver.GetActions(RequestedDatabaseAction.Create)).Return(actions);
                Expect.Call(locator.CreateInstance(DatabaseAction.Create)).Return(creator);
                Expect.Call(locator.CreateInstance(DatabaseAction.Update)).Return(updater);
            }

            using (mocks.Playback())
            {
                IDatabaseActionExecutorFactory factory = new DatabaseActionExecutorFactory(resolver, locator);
                IEnumerable<IDatabaseActionExecutor> executors = factory.GetExecutors(RequestedDatabaseAction.Create);
                IList<IDatabaseActionExecutor> executorList = new List<IDatabaseActionExecutor>(executors);

                Assert.That(executorList, Is.EqualTo(new IDatabaseActionExecutor[]{ creator, updater }));
            }

            mocks.VerifyAll();
        }
		public void SetJavaPath()
		{
			string expectedFileName = "config/wrapper.conf";
			string expectedWrapperJavaSetting = "wrapper.java.setting";
			string expectedLocalJavaExePath = "c:/localjavapath/java.exe";
			var mockRepository = new MockRepository();

			// Arrange
			var fileManipulation = mockRepository.StrictMock<IFileManipulation>();
			var paths = mockRepository.StrictMock<IPaths>();

			var neo4JManager = new Neo4jManager(fileManipulation, null);

			paths.Expect(p => p.LocalJavaExePath).Return(expectedLocalJavaExePath);
			paths.Expect(p => p.Neo4jWrapperSettingJavaCommand).Return(expectedWrapperJavaSetting);
			paths.Expect(p => p.Neo4jWrapperConfigPath).Return(expectedFileName);
			fileManipulation.Expect(fm => fm.ReplaceConfigLine(null, null)).IgnoreArguments();

			mockRepository.ReplayAll();

			// Act
			neo4JManager.SetJavaPath(paths);

			// Assert
			mockRepository.VerifyAll();
		}
		public void Correctly_locates_sql_scripts_and_return_in_asc_order()
		{
			string scriptFolder = @"c:\scripts";

			string[] updateSqlFiles = new string[] { "02_Update.sql", "01_Update.sql" };

			MockRepository mocks = new MockRepository();
			IFileSystem fileSystem = mocks.CreateMock<IFileSystem>();

			using (mocks.Record())
			{
				Expect.Call(fileSystem.GetAllFilesWithExtensionWithinFolder(@"c:\scripts\Update", "sql")).Return(updateSqlFiles);
			}

			using (mocks.Playback())
			{
				ISqlFileLocator fileLocator = new SqlFileLocator(fileSystem);
				string[] sqlFilenames = fileLocator.GetSqlFilenames(scriptFolder, "Update");

				Assert.AreEqual(2, sqlFilenames.Length);
				Assert.AreEqual("01_Update.sql", sqlFilenames[0]);
				Assert.AreEqual("02_Update.sql", sqlFilenames[1]);
			}

			mocks.VerifyAll();
		}
Beispiel #24
0
        public void TestChainOneLink()
        {
            MockRepository mocks = new MockRepository();
            var web = mocks.StrictMock<IWebInteractor>();
            var site = new Website("www.whocares.com", "whatever");
            var mockFSI = MockRepository.GenerateStub<IFileSystemInteractor>();

            CrawlResult testResult = new CrawlResult();
            testResult.ReturnCode = 200;
            testResult.ReturnStatus = "OK";
            testResult.Html = "href=\"/csse.html\"";

            var resultTwo = new CrawlResult();
            resultTwo.ReturnCode = 200;
            resultTwo.ReturnStatus = "OK";
            resultTwo.Html = "";

            Expect.On(web).Call(web.GetPage("www.test.com")).Return(testResult);
            Expect.On(web).Call(web.GetPage("www.test.com/csse.html")).Return(resultTwo);

            mocks.ReplayAll();

            Bot b = new Bot(new Website("www.test.com","simplepath"),null,null,web,mockFSI);
            List<CrawlResult> results = b.CrawlSite(2);

            mocks.VerifyAll();

            Assert.AreEqual(2,results.Count);
        }
Beispiel #25
0
        public void NavigateTo(bool simulateSuccess)
        {
            MockRepository mocks = new MockRepository();

            IGallioNavigator navigator = mocks.StrictMock<IGallioNavigator>();
            using (mocks.Record())
            {
                Expect.Call(navigator.NavigateTo(
                        @"C:\Source\MbUnit\v3\src\Gallio\Gallio.Tests\Reflection\Impl\CecilReflectionPolicyTest.cs", 5, 11))
                    .Return(simulateSuccess);
            }

            using (mocks.Playback())
            {
                InstrumentedProgram program = new InstrumentedProgram();
                program.Engine = navigator;
                int returnCode = program.Run(new string[]
                {
                    @"gallio:navigateTo?path=C:\Source\MbUnit\v3\src\Gallio\Gallio.Tests\Reflection\Impl\CecilReflectionPolicyTest.cs&line=5&column=11"
                });

                Assert.IsFalse(program.HelpCalled);
                Assert.AreEqual(simulateSuccess ? 0 : 1, returnCode);

                mocks.VerifyAll();
            }
        }
		public void Manages_database()
		{
			var settings = new ConnectionSettings("server", "db", true, null, null);
            var scriptDirectory = @"c:\scripts"; 
            var taskAttributes = new TaskAttributes(settings, scriptDirectory);
            taskAttributes.RequestedDatabaseAction= RequestedDatabaseAction.Create;
			var mocks = new MockRepository();
			var taskObserver = mocks.StrictMock<ITaskObserver>();
            var generator = mocks.StrictMock<ILogMessageGenerator>();
            var factory = mocks.StrictMock<IDatabaseActionExecutorFactory>();

            var creator = mocks.StrictMock<IDatabaseActionExecutor>();
            var updater = mocks.StrictMock<IDatabaseActionExecutor>();

			var executors = new IDatabaseActionExecutor[] { creator, updater };

			using (mocks.Record())
			{
				Expect.Call(generator.GetInitialMessage(taskAttributes)).Return("starting...");
				taskObserver.Log("starting...");
				Expect.Call(factory.GetExecutors(RequestedDatabaseAction.Create)).Return(executors);

                creator.Execute(taskAttributes, taskObserver);
                updater.Execute(taskAttributes, taskObserver);
			}

			using (mocks.Playback())
			{
				ISqlDatabaseManager manager = new SqlDatabaseManager(generator, factory);

				manager.Upgrade(taskAttributes, taskObserver);
			}

			mocks.VerifyAll();
		}
		public void IsNotInvokedIfServiceObjectThrowsException()
		{
            MockRepository repository = new MockRepository();
            IMethodInvocation mockInvocation = (IMethodInvocation)repository.CreateMock(typeof(IMethodInvocation));
            IAfterReturningAdvice mockAdvice = (IAfterReturningAdvice)repository.CreateMock(typeof(IAfterReturningAdvice));
            mockAdvice.AfterReturning(null, null, null, null);
            LastCall.IgnoreArguments();
            LastCall.Throw(new FormatException());

            Expect.Call(mockInvocation.Method).Return(ReflectionUtils.GetMethod(typeof(object), "HashCode", new Type[] { }));
            Expect.Call(mockInvocation.Arguments).Return(null);
            Expect.Call(mockInvocation.This).Return(new object());
            Expect.Call(mockInvocation.Proceed()).Return(null);

            repository.ReplayAll();

            try
            {
                AfterReturningAdviceInterceptor interceptor = new AfterReturningAdviceInterceptor(mockAdvice);
                interceptor.Invoke(mockInvocation);
                Assert.Fail("Must have thrown a FormatException by this point.");
            }
            catch (FormatException)
            {
            }

            repository.VerifyAll();

		}
		public void Correctly_assigns_current_user_to_role()
		{
			MockRepository mocks = new MockRepository();

			IPrincipal principal = mocks.CreateMock<IPrincipal>();
			IIdentity identity = mocks.CreateMock<IIdentity>();
			IWebContext context = mocks.CreateMock<IWebContext>();
			IPrincipalFactory principalFactory = mocks.CreateMock<IPrincipalFactory>();

			using (mocks.Record())
			{
				Expect.Call(context.GetUserIdentity()).Return(identity);
				Expect.Call(principalFactory.CreatePrincipal(identity, "Administrator", "Other Role")).Return(principal);
				context.SetUser(principal);
			}

			mocks.ReplayAll();

			using (mocks.Playback())
			{
				IRoleAssigner assigner = new RoleAssigner(context, principalFactory);
				assigner.AssignCurrentUserToRoles("Administrator", "Other Role");
			}

			mocks.VerifyAll();
		}
        public void GetGigsBySiteAfterDate_Calls_GigDAO_Method_GetGigsBySiteAfterDate_Once_And_Returns_Gigs()
        {
            MockRepository mocks = new MockRepository();

            DateTime startDate = DateTime.Now;
            int numGigs = 10;
            List<Gig> gigs = (List<Gig>)CreateListOfGigs(numGigs, startDate);

            Guid siteId = Guid.NewGuid();

            IGigDAO gigDAO = mocks.DynamicMock<IGigDAO>();
            GigManager gigManager = new GigManager();
            gigManager.GigDAO = gigDAO;

            Expect.Call(gigDAO.GetGigsBySiteAfterDate(siteId, startDate))
               .Constraints(new AbstractConstraint[] { Is.Equal(siteId), Is.Equal(startDate) })
               .Repeat.Once()
               .Return(gigs);

            mocks.ReplayAll();

            List<Gig> result = (List<Gig>)gigManager.GetGigsBySiteAfterDate(siteId, startDate);

            mocks.VerifyAll();
        }
        public void Drops_Azure_database_without_dropping_connections()
        {
            var settings = new ConnectionSettings("server", "db", true, null, null);
            var taskAttributes = new TaskAttributes(settings, null);

            var mocks = new MockRepository();
            var connectionDropper = mocks.StrictMock<IDatabaseConnectionDropper>();
            var taskObserver = mocks.StrictMock<ITaskObserver>();
            var queryExecutor = mocks.StrictMock<IQueryExecutor>();

            using (mocks.Record())
            {
                Expect.Call(() => taskObserver.Log("Running against: SQL Azure"));
                Expect.Call(queryExecutor.ReadFirstColumnAsStringArray(settings, "select @@version")).Return(new string[] { "SQL Azure" });
                queryExecutor.ExecuteNonQuery(settings, "drop database [db]");
                Expect.Call(() => taskObserver.Log("Dropping database: db\n"));
            }

            using (mocks.Playback())
            {
                IDatabaseActionExecutor dropper = new DatabaseDropper(connectionDropper, queryExecutor);
                dropper.Execute(taskAttributes, taskObserver);
            }

            mocks.VerifyAll();
        }
Beispiel #31
0
        public async Task C_F_RhinoMocksDynamicMockDoesntWorkWell()
        {
            var mocks   = new Rhino.Mocks.MockRepository();
            var service = mocks.DynamicMock <IService>();
            var sut     = new Sut
            {
                Service = service
            };

            mocks.ReplayAll();
            await sut.UseServiceAsync();

            mocks.VerifyAll();
        }
Beispiel #32
0
        public async Task C_G_RhinoMocksButIfYouExplicitlyExpectThenOfCourseItWorks()
        {
            var mocks   = new Rhino.Mocks.MockRepository();
            var service = mocks.DynamicMock <IService>();

            Expect.Call(service.DoSomethingAsync()).Return(Task.CompletedTask);
            var sut = new Sut
            {
                Service = service
            };

            mocks.ReplayAll();
            await sut.UseServiceAsync();

            mocks.VerifyAll();
        }
        public void Get_Must_Revalidate_Etag_NotModified()
        {
            // setup
            var request           = new HttpRequestMessage(HttpMethod.Get, DummyUrl);
            var responseFromCache = GetOkMessage(true);

            responseFromCache.Headers.ETag            = new EntityTagHeaderValue(ETagValue);
            responseFromCache.Content.Headers.Expires = DateTime.Now.Subtract(TimeSpan.FromSeconds(10));
            var responseFromServer = new HttpResponseMessage(HttpStatusCode.NotModified);

            _messageHandler.Response = responseFromServer;
            _cacheStore.Expect(
                x => x.TryGetValue(Arg <CacheKey> .Is.Anything, out Arg <HttpResponseMessage> .Out(responseFromCache).Dummy))
            .Return(true);
            _cacheStore.Expect(x => x.AddOrUpdate(Arg <CacheKey> .Is.Anything, Arg <HttpResponseMessage> .Is.Anything));

            _mockRepository.ReplayAll();

            // run
            var            task             = _client.SendAsync(request);
            var            responseReturned = task.Result;
            var            header           = responseReturned.Headers.Single(x => x.Key == CacheCowHeader.Name);
            CacheCowHeader cacheCowHeader   = null;

            CacheCowHeader.TryParse(header.Value.First(), out cacheCowHeader);

            // verify
            _mockRepository.VerifyAll();
            Assert.IsNotNull(cacheCowHeader);
            Assert.AreEqual(ETagValue, request.Headers.IfNoneMatch.First().Tag);
            Assert.AreSame(responseFromCache, responseReturned);
            Assert.AreEqual(true, cacheCowHeader.CacheValidationApplied);
        }
Beispiel #34
0
        public void Get_OK_But_Not_In_Cache_To_Insert_In_Cache()
        {
            // setup
            var request  = new HttpRequestMessage(HttpMethod.Get, DummyUrl);
            var response = GetOkMessage();

            _messageHandler.Response = response;
            _cacheStore.Expect(x => x.TryGetValue(Arg <CacheKey> .Is.Anything,
                                                  out Arg <HttpResponseMessage> .Out(null).Dummy)).Return(false);
            _cacheStore.Expect(x => x.AddOrUpdate(Arg <CacheKey> .Is.Anything,
                                                  Arg <HttpResponseMessage> .Is.Same(response)));

            _mockRepository.ReplayAll();

            // run
            var            task             = _client.SendAsync(request);
            var            responseReturned = task.Result;
            var            header           = responseReturned.Headers.Single(x => x.Key == CacheCowHeader.Name);
            CacheCowHeader cacheCowHeader   = null;

            CacheCowHeader.TryParse(header.Value.First(), out cacheCowHeader);
            // verify
            _mockRepository.VerifyAll();

            Assert.IsNotNull(cacheCowHeader);
            Assert.AreEqual(true, cacheCowHeader.DidNotExist);
        }