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();


        }
Esempio n. 3
0
        public void FeedbackCreateCallsCommentService(bool isSpam, bool isAdmin)
        {
            Assert.IsTrue(Config.CreateBlog("", "username", "password", _hostName, string.Empty));
            MockRepository mocks = new MockRepository();
            IFeedbackSpamService service = (IFeedbackSpamService)mocks.CreateMock(typeof(IFeedbackSpamService));
            Config.CurrentBlog.FeedbackSpamService = service;
            Config.CurrentBlog.DuplicateCommentsEnabled = true;
            Config.CurrentBlog.FeedbackSpamServiceKey = "my-secret-key";
            Config.CurrentBlog.ModerationEnabled = false;
            FeedbackItem feedback = new FeedbackItem(FeedbackType.Comment);
            Expect.Call(service.IsSpam(feedback)).Return(isSpam);
            feedback.Title = "blah";
            feedback.Body = UnitTestHelper.GenerateRandomString();
            mocks.ReplayAll();

            Assert.AreEqual(isAdmin, SecurityHelper.IsAdmin);

            try
            {
                FeedbackItem.Create(feedback, new CommentFilter(new Cache()));
            }
            catch(BaseCommentException)
            {
            }
            Assert.AreEqual(!isSpam, feedback.Approved);
        }
        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();
        }
Esempio n. 5
0
        public virtual void RunOnceBeforeAny()
        {
            // Initialize NBuilder settings
            BuilderSetup.SetDefaultPropertyNamer(new NonDefaultNonRepeatingPropertyNamer(new ReflectionUtil()));

            // Create a mock repository for new mocks
            mocks = new MockRepository();
            
            EstablishContext();

            // Stop recording
            mocks.ReplayAll();

            try
            {
                // Allow execution of code just prior to test execution
                BeforeExecuteTest();

                // Execute the test
                ExecuteTest();
            }
            finally
            {
                // Allow cleanup surrounding test execution, prior to final cleanup
                AfterExecuteTest();
            }
        }
        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;
        }
Esempio n. 7
0
        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 void Setup()
		{
			basketRepository = MockRepository.GenerateStub<IRepository<Basket>>();
			unitOfWorkManager = MockRepository.GenerateStub<IUnitOfWorkManager>();

			userService = MockRepository.GenerateStub<IUserService>();
			postageService = MockRepository.GenerateStub<IPostageService>();
			countryRepository = MockRepository.GenerateStub<IRepository<Country>>();
			cardTypeRepository = MockRepository.GenerateStub<IRepository<CardType>>();
			orderRepository = MockRepository.GenerateStub<IRepository<Order>>();
			subscriptionRepository = MockRepository.GenerateStub<IRepository<MailingListSubscription>>();
			emailService = MockRepository.GenerateStub<IEmailService>();

			var mocks = new MockRepository(); //TODO: No need to partial mock once email sending is fixed
			controller = new CheckoutController(
				basketRepository,
				userService,
				postageService,
				countryRepository,
				cardTypeRepository,
				orderRepository,
				unitOfWorkManager,
				emailService,
				subscriptionRepository
			);
			mocks.ReplayAll();
			userService.Expect(us => us.CurrentUser).Return(new User { UserId = 4, RoleId = Role.AdministratorId });
		}
Esempio n. 9
0
 /// <summary>
 /// Creates a mocked datareader and loads it with row data ready to replay
 /// </summary>
 /// <param name="mocks">The mock repository object that all the tests are running with</param>
 /// <param name="procedureName">The name of the procedure you want to call</param>
 /// <param name="creator">The new DataReaderCreator object</param>
 /// <param name="reader">The new DataReader object</param>
 /// <param name="testRowData">A list of test row data to load the reader with</param>
 static public void CreateMockedDataBaseObjects(MockRepository mocks, string procedureName, out IDnaDataReaderCreator creator, out IDnaDataReader reader, List<TestDatabaseRow> testRowData)
 {
     reader = CreateMockedIDnaDataReader(mocks, testRowData);
     creator = mocks.DynamicMock<IDnaDataReaderCreator>();
     creator.Stub(x => x.CreateDnaDataReader(procedureName)).Return(reader);
     mocks.ReplayAll();
 }
Esempio n. 10
0
		public static void TestCacheInvalidationForPost(string method)
		{
		    const string relatedUrl = "http://api/SomeLocationUrl/";
			// setup
			var locationUrl = new Uri(relatedUrl);
			var mocks = new MockRepository();
			var request = new HttpRequestMessage(new HttpMethod(method), TestUrl);
			string routePattern = "http://myserver/api/stuffs/*";
			var entityTagStore = mocks.StrictMock<IEntityTagStore>();

			var cachingHandler = new CachingHandler(new HttpConfiguration(), entityTagStore)
			{
				
			};
			var entityTagKey = new CacheKey(TestUrl, new string[0], routePattern);
			var response = new HttpResponseMessage();
			response.Headers.Location = locationUrl;
			var invalidateCacheForPost = cachingHandler.PostInvalidationRule(entityTagKey, request, response);
			if(method == "POST")
			{
                entityTagStore.Expect(x => x.RemoveAllByRoutePattern("/SomeLocationUrl/")).Return(1);				
			}
			mocks.ReplayAll();

			// run
			invalidateCacheForPost();

			// verify
			mocks.VerifyAll();

			
		}
Esempio n. 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();
        }
Esempio n. 12
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();
        }
Esempio n. 13
0
        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);
        }
Esempio n. 14
0
        public void TestIndirectBlocks()
        {
            var repository = new MockRepository();
            var mockDiskAccess = repository.DynamicMock<IDirectDiskAccess>();
            var mockAllocator = repository.StrictMock<IBlockAllocator>();

            const int blocksToAllocate = 2000;
            var list = new List<Address>();
            for (int i = 0; i < blocksToAllocate; ++i)
            {
                list.Add(new Address((ulong)i * Constants.BlockSizeBytes));
            }

            Expect.Call(mockAllocator.AllocateBlocks(blocksToAllocate)).IgnoreArguments().Return(list.ToArray());
            Expect.Call(mockAllocator.AllocateBlocks(1)).IgnoreArguments().Return(new[] { new Address(0) }).Repeat.Times(3); // indirect block allocation
            Expect.Call(() => mockAllocator.FreeBlocks(null)).IgnoreArguments().Repeat.Any();

            var storage = new BlockAddressStorage(mockDiskAccess, mockAllocator, new Address(0), new Address(0));

            repository.ReplayAll();

            storage.AddBlocks(2000);
            storage.GetBlockStartAddress(12);
            storage.GetBlockStartAddress(1024);
            storage.GetBlockStartAddress(1024 + 12);
            storage.GetBlockStartAddress(1999);
            Assert.Throws<IndexOutOfRangeException>(() => storage.GetBlockStartAddress(2000));

            repository.VerifyAll();
        }
        public void Initalize_Sets_URL_On_View()
        {
            MockRepository repo = new MockRepository();
            IOptionsView mockOptionsView = repo.StrictMock<IOptionsView>();
            ISettingsOriginator mockSettingsOriginator = repo.StrictMock<ISettingsOriginator>();
            ISettingsMemento mockSettingsMemento = repo.StrictMock<ISettingsMemento>();
            ISetting urlSetting = repo.StrictMock<ISetting>();
            ISetting userNameSetting = repo.StrictMock<ISetting>();
            ISetting passwordSetting = repo.StrictMock<ISetting>();
            string url = "http://www.google.com";
            string userName = "******";
            string password = "******";

            urlSetting.Expect(set => set.Value).Return(url);
            userNameSetting.Expect(set => set.Value).Return(userName);
            passwordSetting.Expect(set => set.Value).Return(password);

            mockSettingsOriginator.Expect(org => org.Get("TrackerURL")).Return(urlSetting);
            mockSettingsOriginator.Expect(org => org.Get("UserName")).Return(userNameSetting);
            mockSettingsOriginator.Expect(org => org.Get("Password")).Return(passwordSetting);
            mockSettingsOriginator.Expect(org => org.GetMemento()).Return(mockSettingsMemento);

            mockOptionsView.Expect(view => view.URL).SetPropertyWithArgument(url);
            mockOptionsView.Expect(view => view.UserName).SetPropertyWithArgument(userName);
            mockOptionsView.Expect(view => view.Password).SetPropertyWithArgument(password);

            repo.ReplayAll();

            IOptionsPresenter pres = new OptionsPresenter(mockOptionsView, mockSettingsOriginator);
            pres.Initalize();

            mockOptionsView.VerifyAllExpectations();
            mockSettingsOriginator.VerifyAllExpectations();
            urlSetting.VerifyAllExpectations();
        }
        public void HasReached_GenerationNumberLowerThanCondition_False()
        {
            var repository = new MockRepository();
            var ga = repository.StrictMock<IGeneticAlgorithm>();

            using (repository.Ordered())
            {
                ga.Expect(g => g.GenerationsNumber).Return(1);
                ga.Expect(g => g.GenerationsNumber).Return(2);
                ga.Expect(g => g.GenerationsNumber).Return(3);
                ga.Expect(g => g.GenerationsNumber).Return(4);
                ga.Expect(g => g.GenerationsNumber).Return(5);
                ga.Expect(g => g.GenerationsNumber).Return(6);
                ga.Expect(g => g.GenerationsNumber).Return(7);
                ga.Expect(g => g.GenerationsNumber).Return(8);
                ga.Expect(g => g.GenerationsNumber).Return(0);
            }
            repository.ReplayAll();

            var target = new GenerationNumberTermination(10);
            Assert.IsFalse(target.HasReached(ga));

            for (int i = 0; i < 8; i++)
            {
                Assert.IsFalse(target.HasReached(ga));
            }

        }
		public void CorrectlyExecutesScriptIfItHasntAlreadyBeenExecuted()
		{
			ConnectionSettings settings = getConnectionSettings();
			string scriptFile = @"c:\scripts\Update\01_Test.sql";
			string fileContents = "file contents...";

			MockRepository mocks = new MockRepository();
			IScriptExecutionTracker executionTracker = mocks.CreateMock<IScriptExecutionTracker>();
			IFileSystem fileSystem = mocks.CreateMock<IFileSystem>();
			IQueryExecutor queryExecutor = mocks.CreateMock<IQueryExecutor>();
			ITaskObserver taskObserver = mocks.CreateMock<ITaskObserver>();

			Expect.Call(executionTracker.ScriptAlreadyExecuted(settings, "01_Test.sql")).Return(false);
			taskObserver.Log("Executing: 01_Test.sql");
			Expect.Call(fileSystem.ReadTextFile(scriptFile)).Return(fileContents);
			queryExecutor.ExecuteNonQuery(settings, fileContents, true);
			executionTracker.MarkScriptAsExecuted(settings, "01_Test.sql", taskObserver);

			mocks.ReplayAll();

			IChangeScriptExecutor executor = new ChangeScriptExecutor(executionTracker, queryExecutor, fileSystem);
			executor.Execute(scriptFile, settings, taskObserver);

			mocks.VerifyAll();
		}
Esempio n. 18
0
        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();
        }
Esempio n. 19
0
        public void Initialize()
        {
            Queue<string> tags = new Queue<string>();
            tags.Enqueue("<2cents>");
            tags.Enqueue("<ale>");
            tags.Enqueue("<yikes>");
            tags.Enqueue(";)");
            tags.Enqueue("<3");
            

            Queue<string> tagTranslation = new Queue<string>();
            tagTranslation.Enqueue("2cents");
            tagTranslation.Enqueue("ale");
            tagTranslation.Enqueue("yikes");
            tagTranslation.Enqueue("winkeye");
            tagTranslation.Enqueue("specialheart");
            
            

            MockRepository mocks = new MockRepository();
            IDnaDataReader reader = mocks.DynamicMock<IDnaDataReader>();
            reader.Stub(x => x.HasRows).Return(true);
            //reader.Stub(x => x.Read()).Return(true).Repeat.Times(4);
            reader.Stub(x => x.Read()).Return(true).Repeat.Times(4);
            reader.Stub(x => x.GetStringNullAsEmpty("name")).Return("").WhenCalled(x => x.ReturnValue = tagTranslation.Dequeue());
            reader.Stub(x => x.GetStringNullAsEmpty("tag")).Return("").WhenCalled(x => x.ReturnValue = tags.Dequeue());
            IDnaDataReaderCreator creator = mocks.DynamicMock<IDnaDataReaderCreator>();
            creator.Stub(x => x.CreateDnaDataReader("getsmileylist")).Return(reader);
            mocks.ReplayAll();

            SmileyTranslator.LoadSmileys(creator);

            ProfanityFilterTests.InitialiseProfanities();
        }
Esempio n. 20
0
        public static void TestCachingContinuation(
			string method,
			bool existsInStore,
			bool addVaryHeader,
			bool addLastModifiedHeader,
			bool alreadyHasLastModified,
			string[] varyByHeader)
        {
            // setup
            var mocks = new MockRepository();
            var request = new HttpRequestMessage(new HttpMethod(method), TestUrl);
            request.Headers.Add(HttpHeaderNames.Accept, "text/xml");
            request.Headers.Add(HttpHeaderNames.AcceptLanguage, "en-GB");
            var entityTagStore = mocks.StrictMock<IEntityTagStore>();
            var cachingHandler = new CachingHandler(entityTagStore, varyByHeader)
                                 	{
                                 		AddLastModifiedHeader = addLastModifiedHeader,
                                        AddVaryHeader = addVaryHeader
                                 	};

            var entityTagHeaderValue = new TimedEntityTagHeaderValue("\"12345678\"");
            var entityTagKey = new EntityTagKey(TestUrl, new string[0]);
            cachingHandler.EntityTagKeyGenerator = (x, y) => entityTagKey;
            cachingHandler.ETagValueGenerator = (x, y) => new EntityTagHeaderValue(entityTagHeaderValue.Tag);
            entityTagStore.Expect(x => x.TryGet(Arg<EntityTagKey>.Matches(etg => etg.ResourceUri == TestUrl),
                out Arg<TimedEntityTagHeaderValue>.Out(entityTagHeaderValue).Dummy)).Return(existsInStore);

            if (!existsInStore  || request.Method == HttpMethod.Put || request.Method == HttpMethod.Post)
            {
                entityTagStore.Expect(
                    x => x.AddOrUpdate(Arg<EntityTagKey>.Matches(etk => etk == entityTagKey),
                        Arg<TimedEntityTagHeaderValue>.Matches(ethv => ethv.Tag == entityTagHeaderValue.Tag)));
            }

            mocks.ReplayAll();

            var response = new HttpResponseMessage();
            response.Content = new ByteArrayContent(new byte[0]);
            if(alreadyHasLastModified)
                response.Content.Headers.Add(HttpHeaderNames.LastModified, DateTimeOffset.Now.ToString("r"));

            var cachingContinuation = cachingHandler.GetCachingContinuation(request);
            var taskCompletionSource = new TaskCompletionSource<HttpResponseMessage>();
            taskCompletionSource.SetResult(response);

            // run
            var httpResponseMessage = cachingContinuation(taskCompletionSource.Task);

            // test
            if(addLastModifiedHeader)
            {
                Assert.That(httpResponseMessage.Content.Headers.Any(x=>x.Key == HttpHeaderNames.LastModified),
                    "LastModified does not exist");
            }
            if(!addLastModifiedHeader && !alreadyHasLastModified)
            {
                Assert.That(!httpResponseMessage.Content.Headers.Any(x => x.Key == HttpHeaderNames.LastModified),
                    "LastModified exists");
            }
        }
Esempio n. 21
0
        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 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();
		}
Esempio n. 23
0
 public static HttpContextBase DynamicHttpContextBase()
 {
     var mocks = new MockRepository();
     var context = mocks.DynamicHttpContextBase();
     mocks.ReplayAll();
     return context;
 }
		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 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();

		}
Esempio n. 26
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);
        }
Esempio n. 27
0
        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();
        }
Esempio n. 28
0
		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();
		}
Esempio n. 29
0
        public void VerifyInstanceDoesNotCallJetTermWhenCreateInstanceFails()
        {
            var mocks = new MockRepository();
            var mockApi = mocks.StrictMock<IJetApi>();
            using (new ApiTestHook(mockApi))
            {
                Expect.Call(
                    mockApi.JetCreateInstance2(
                        out Arg<JET_INSTANCE>.Out(JET_INSTANCE.Nil).Dummy,
                        Arg<string>.Is.Anything,
                        Arg<string>.Is.Anything,
                        Arg<CreateInstanceGrbit>.Is.Anything))
                    .Return((int) JET_err.InvalidName);
                mocks.ReplayAll();

                try
                {
                    using (var instance = new Instance("testfail"))
                    {
                        Assert.Fail("Expected an EsentErrorException");
                    }
                }
                catch (EsentErrorException)
                {
                    // expected
                }

                mocks.VerifyAll();
            }
        }
Esempio n. 30
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();
        }
Esempio n. 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();
        }
Esempio n. 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);
        }
Esempio n. 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);
        }