public void Setup()
 {
     mr = new MockRepository();
     frame = mr.DynamicMock<IWindowFrame>();
     sc = new ServiceContainer();
     sc.AddService(typeof(IWindowFrame), frame);
 }
Beispiel #2
0
 public void Add()
 {
     var mocks = new MockRepository();
     var connection = mocks.StrictMock<ISolrConnection>();
     var executer = mocks.StrictMock<ISolrQueryExecuter<TestDocumentWithoutUniqueKey>>();
     var headerParser = mocks.StrictMock<ISolrHeaderResponseParser>();
     var docSerializer = new SolrDocumentSerializer<TestDocumentWithoutUniqueKey>(new AttributesMappingManager(), new DefaultFieldSerializer());
     With.Mocks(mocks)
         .Expecting(() => {
             Expect.On(connection)
                 .Call(connection.Post("/update", "<add><doc /></add>"))
                 .Repeat.Once()
                 .Return(EmbeddedResource.GetEmbeddedString(GetType(), "Resources.response.xml"));
             Expect.On(headerParser)
                 .Call(headerParser.Parse(null))
                 .IgnoreArguments()
                 .Return(new ResponseHeader());
         })
         .Verify(() => {
             var ops = new SolrBasicServer<TestDocumentWithoutUniqueKey>(connection, executer, docSerializer, null, headerParser, null, null, null);
             ops.AddWithBoost(new[] {
                 new KeyValuePair<TestDocumentWithoutUniqueKey, double?>(new TestDocumentWithoutUniqueKey(), null),
             }, null);
         });
 }
Beispiel #3
0
        public static void RelationsTest()
        {
            MockRepository rhinoEngine = new MockRepository();
            var mockWriter = rhinoEngine.DynamicMock<TextWriter>();

            TextWriterFactory.SetTextWriter(mockWriter);

            using (rhinoEngine.Record())
            {
                mockWriter.Write("Nothing");
                LastCall.Constraints(new Rhino.Mocks.Constraints.Contains("TestCustomer") &
                                     new Rhino.Mocks.Constraints.Contains("TestMovie") &
                                     new Rhino.Mocks.Constraints.Contains("6 days") &
                                     new Rhino.Mocks.Constraints.Contains(12.ToString("C")));
                mockWriter.Flush();

            }

            Customer customer = new Customer("TestCustomer");
            customer.Rental.Add(new Rental(new Movie("TestMovie", 2), 6));

            ReportManager.CreateReport("SomePath", customer);

            rhinoEngine.VerifyAll();
        }
        public void ReturnResultsFromMock()
        {
            MockRepository mocks = new MockRepository();
            IGetResults resultGetter = mocks.DynamicMock<IGetResults>();

            using (mocks.Record())
            {
                resultGetter.GetSomeNumber("a");
                LastCall.Return(1);

                resultGetter.GetSomeNumber("c");
                LastCall.Return(2);

                resultGetter.GetSomeNumber("b");
                LastCall.Return(3);
            }

            int result;

            result = resultGetter.GetSomeNumber("b");
            Assert.AreEqual(3, result);

            result = resultGetter.GetSomeNumber("a");
            Assert.AreEqual(1, result);

            result = resultGetter.GetSomeNumber("c");
            Assert.AreEqual(2, result);
        }
        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();


        }
Beispiel #6
0
 public void Setup()
 {
     mr = new MockRepository();
     sc = new ServiceContainer();
     cfgSvc = mr.Stub<IConfigurationService>();
     sc.AddService<IConfigurationService>(cfgSvc);
 }
 public void BeginTest()
 {
     repo = new MockRepository();
     channelFactory = repo.StrictMock<ICanCreateChannels<IService>>();
     communicationObject = repo.StrictMultiMock<ICommunicationObject>(typeof(IService));
     manager = new SingleActionChannelManager<IService>(channelFactory);
 }
        public void ShouldParseAuthenticationStringWhenAuthorizationStringIsAvailable()
        {
            MockRepository repository = new MockRepository();

             DigestHeaderParser headerParser = MockCreator<DigestHeaderParser>.Stub(repository);
             MethodExtractor methodExtractor = MockCreator<MethodExtractor>.Stub(repository);

             Message testMessage = TestResources.CreateMessage();

             AuthorizationStringExtractor extractor;
             using (repository.Record())
             {
            headerParser.Expect(parser => parser.Parse(string.Empty)).IgnoreArguments().Return(TestResources.CreateHeader());

            extractor = MockCreator<AuthorizationStringExtractor>.Create(repository);
            string authenticationString;
            extractor.Expect(extr => extr.TryExtractAuthorizationHeader(testMessage, out authenticationString)).OutRef(TestResources.AuthenticationString).Return(true);
             }

             var digestHeaderExtractor = new DigestHeaderExtractor(extractor, headerParser, methodExtractor);
             using (repository.Playback())
             {
            DigestHeader digestHeader;
            bool result = digestHeaderExtractor.TryExtract(testMessage, out digestHeader);
            Assert.That(result, Is.True);
             }
        }
        public void Save_ThrowsExceptionOnSave_SavesLog()
        {
            var user = new User()
            {
                Name  = "John",
                Email = "*****@*****.**"
            };

            var exception = new Exception("Fail to connect to database");

            var emailValidation = MockRepository.GenerateStub <IEmailValidation>();
            var userRepository  = MockRepository.GenerateStub <IUserRepository>();
            var logService      = MockRepository.GenerateMock <ILogService>();

            emailValidation.Stub(p => p.isValid(It.IsAny <string>())).Return(true);
            userRepository.Stub(p => p.Save(It.Is <User>(u => u.Equals(user)))).Throw(exception);
            logService.Expect(p => p.LogError(It.Is <Exception>(e => e.Equals(exception))));

            var userService = new UserService(userRepository, emailValidation);

            userService.LogService = logService;

            userService.Save(user);

            userRepository.VerifyAllExpectations();
        }
 public void Setup()
 {
     repository = new MockRepository();
     sc = new ServiceContainer();
     arch = new IntelArchitecture(ProcessorMode.Protected32);
     dcSvc = repository.StrictMock<IConfigurationService>();
 }
        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();
        }
Beispiel #12
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 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 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 Should_enable_load_balancing_when_requested()
		{
			ApplicationInstance instance = new ApplicationInstance();
			instance.AvailableForLoadBalancing = false;

			MockRepository mocks = new MockRepository();
			IApplicationInstanceContext instanceContext = mocks.CreateMock<IApplicationInstanceContext>();
			IWebContext context = mocks.CreateMock<IWebContext>();
			ISecureAvailabilityStatusUpdater updater = mocks.CreateMock<ISecureAvailabilityStatusUpdater>();			

			using (mocks.Record())
			{
				Expect.Call(instanceContext.GetCurrent()).Return(instance);
				Expect.Call(context.GetRequestItem(LoadBalanceStatusManager.ENABLED_PARAM)).Return("True");
				Expect.Call(updater.SetStatus(true)).Return("My error message");
			}

			using (mocks.Playback())
			{
				ILoadBalanceStatusManager manager = new LoadBalanceStatusManager(instanceContext, context, updater);
				string errorMessage = manager.HandleLoadBalanceRequest();

				Assert.That(errorMessage, Is.EqualTo("My error message"));
			}
		}
        public void SetUp()
        {
            mocks = new MockRepository();
            instance = mocks.DynamicMock<IUnitOfWork>();

            store = new ThreadedUnitOfWorkStore();
        }
Beispiel #17
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();
            }
        }
Beispiel #18
0
 public void SetUp()
 {              
     mockRepository = new MockRepository();
     mainTransport = mockRepository.StrictMultiMock<ITransport>();
     mainTransport.Replay();
     retryingTransport = new RetryingTransport(new SilentLogger(), mainTransport, retryCount, retryDelay);
 }
        public void CanCreateWithDefaults()
        {
            string SESSIONFACTORY_OBJECTNAME = ConfigSectionSessionScopeSettings.DEFAULT_SESSION_FACTORY_OBJECT_NAME;

            // setup expected values
            MockRepository mocks = new MockRepository();
            ISessionFactory expectedSessionFactory = mocks.StrictMock<ISessionFactory>();
            IInterceptor expectedEntityInterceptor = null;
            bool expectedSingleSession = SessionScopeSettings.SINGLESESSION_DEFAULT;
            FlushMode expectedDefaultFlushMode = SessionScopeSettings.FLUSHMODE_DEFAULT;

            // create and register context
            StaticApplicationContext appCtx = new StaticApplicationContext();
            appCtx.Name = AbstractApplicationContext.DefaultRootContextName;
            appCtx.ObjectFactory.RegisterSingleton(SESSIONFACTORY_OBJECTNAME, expectedSessionFactory);
            ContextRegistry.Clear();
            ContextRegistry.RegisterContext(appCtx);

            ConfigSectionSessionScopeSettings settings = new ConfigSectionSessionScopeSettings(this.GetType(), (IVariableSource)null);

            Assert.AreEqual(expectedSessionFactory, settings.SessionFactory);
            Assert.AreEqual(expectedEntityInterceptor, settings.EntityInterceptor);
            Assert.AreEqual(expectedSingleSession, settings.SingleSession);
            Assert.AreEqual(expectedDefaultFlushMode, settings.DefaultFlushMode);
        }
        public void ExecuteWithAllOptions()
        {
            var mocks = new MockRepository();
            var conn = mocks.StrictMock<ISolrConnection>();

            With.Mocks(mocks).Expecting(() =>
            {
                conn.Post("/update", "<commit waitSearcher=\"true\" waitFlush=\"true\" expungeDeletes=\"true\" maxSegments=\"2\" />");
                LastCall.On(conn).Repeat.Once().Do(new Writer(delegate(string ignored, string s)
                {
                    Console.WriteLine(s);
                    return null;
                }));
            }).Verify(() =>
            {
                var cmd = new CommitCommand
                              {
                                  MaxSegments = 2,
                                  ExpungeDeletes = true,
                                  WaitFlush = true,
                                  WaitSearcher = true
                              };
                cmd.Execute(conn);
            });
        }
 public void InitializeTest()
 {
     _mockScheduleRepository     = MockRepository.GenerateMock <IScheduleRepository>();
     _scheduleController         = new ScheduleController(_mockScheduleRepository);
     _templateScheduleController = new TemplateScheduleController();
     _templateShiftController    = new TemplateShiftController(new TemplateShiftRepository());
 }
        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();
        }
Beispiel #23
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();
            }
        }
Beispiel #24
0
		public void TestFixtureSetUp()
		{
			Mocks = new MockRepository();

			Establish_context();
			Because();
		}
Beispiel #25
0
		public void Setup()
		{
			ssaIds = new SsaIdentifierCollection();
            mr = new MockRepository();
            arch = mr.Stub<IProcessorArchitecture>();
            importResolver = mr.Stub<IImportResolver>();
		}
        public void SetUp()
        {
            _mocks = new MockRepository();
            _output = new StringWriter();

            string viewPath = "MvcContrib.ViewEngines.NVelocity.Tests";

            IDictionary properties = new Hashtable();
            properties["resource.loader"] = "assembly";
            properties["assembly.resource.loader.class"] = "NVelocity.Runtime.Resource.Loader.AssemblyResourceLoader, NVelocity";
            properties["assembly.resource.loader.assembly"] = new List<string>() {GetType().Assembly.FullName};
            properties["master.folder"] = viewPath;
            _viewEngine = new NVelocityViewEngine(properties);

            var httpContext = _mocks.DynamicMock<HttpContextBase>();
            var response = _mocks.DynamicMock<HttpResponseBase>();
            SetupResult.For(httpContext.Response).Return(response);
            SetupResult.For(response.Output).Return(_output);

            var requestContext = new RequestContext(httpContext, new RouteData());
            var controller = _mocks.DynamicMock<ControllerBase>();

            _mocks.ReplayAll();

            _controllerContext = new ControllerContext(requestContext, controller);
            _controllerContext.RouteData.Values.Add("controller", viewPath);
        }
        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);
        }
Beispiel #28
0
 public CollectionFieldParser CreateCollectionFieldParser()
 {
     var mocks = new MockRepository();
     var vp = mocks.CreateMock<ISolrFieldParser>();
     var p = new CollectionFieldParser(vp);
     return p;
 }
 public void Setup()
 {
     mr = new MockRepository();
     mockFactory = new MockFactory(mr);
     arch = new PowerPcArchitecture32();
     platform = new SysVPlatform(null, arch);
 }
        public void Do3Fluent()
        {
            var mockRepository = new MockRepository();
            var view = mockRepository.StrictMock<IButtonView>();
            var model = mockRepository.StrictMock<IToggleModel>();

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

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

            IEventSubscriber subscriber = mockRepository.StrictMock<IEventSubscriber>();
            IWithEvents events = new WithEvents();
            // This doesn't create an expectation because no method is called on subscriber!!
            events.Blah += subscriber.Handler;
            subscriber.Handler(VisibilityState.Visible);

            With.Mocks(mockRepository)
                .Expecting(delegate
                           	{
                           		Expect.Call(model.ToggleVisibility);
                           		Expect.Call(() => model.VisibilityStateChanged += null).IgnoreArguments();
                           		Expect.Call(() => view.SetCheckedState(CheckedState.Checked));
                           	})
                .Verify(delegate
                            {
                                events.RaiseEvent(VisibilityState.Visible);
                                //clicked.Raise();
                            });
        }
 public void SetUp()
 {
     mockery = new MockRepository();
     blogPostService = mockery.DynamicMock<IBlogPostService>();
     controller = new PostController(blogPostService);
     PrepareController(controller, "post");
 }
        public void SetUp()
        {
            _mockRepository = new MockRepository();
            _tagRepository = _mockRepository.DynamicMock<IRepository<Tag>>();

            _tagService = new TagService(_tagRepository);
        }
        public void IsMockableWithRhino()
        {
            var paletteHelper = MockRepository.GenerateStub <PaletteHelper>();

            paletteHelper.SetLightDark(true);

            paletteHelper.AssertWasCalled(ph => ph.SetLightDark(true));
        }
Beispiel #34
0
 public void Setup()
 {
     _mockRepository = new MockRepository();
     _cacheStore     = _mockRepository.StrictMock <ICacheStore>();
     _messageHandler = new DummyMessageHandler();
     _cachingHandler = new CachingHandler(_cacheStore)
     {
         InnerHandler = _messageHandler
     };
     _client = new HttpClient(_cachingHandler);
 }
        public void Rhino_onSpecificDrugsRetrieved_WhenEventRaised_DrugServiceListens()
        {
            // Arrange
            var mockDrugService = MockRepository.GenerateMock <IDrugService>();

            _dataAccess.SpecificDrugRetrievedEvent += mockDrugService.OnSpecificDrugsRetrieved;

            // Act
            _dataAccess.GetSpecificDrugs(_drugIds);

            // Assert
            mockDrugService.AssertWasCalled(ds => ds.OnSpecificDrugsRetrieved(Arg <object> .Is.Equal(_dataAccess), Arg <SpecificDrugRetrievedArgs> .Matches(a => Equals(a.DrugIds, _drugIds))));
        }
        public void About()
        {
            // Arrange
            var mockRepo           = new Rhino.Mocks.MockRepository();
            var mockTwitterService = mockRepo.StrictMock <ITwitterService>();

            var controller = new HomeController(new InMemoryRepository(), null, mockTwitterService);

            // Act
            var result = controller.About() as ViewResult;

            // Assert
            Assert.IsNotNull(result);
        }
Beispiel #37
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();
        }
        public void Save_InvalidEmail_ThrowsException()
        {
            var user = new User()
            {
                Name  = "John",
                Email = "email"
            };

            var emailValidation = MockRepository.GenerateStub <IEmailValidation>();

            emailValidation.Stub(p => p.isValid(It.IsAny <string>())).Return(false);

            var userService = new UserService(null, emailValidation);

            Assert.Throws(typeof(ArgumentException), () => userService.Save(user), "Email is invalid");
        }
Beispiel #39
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 Rhino_Exception()
        {
            // Arrange
            var mockDataAccess = MockRepository.GenerateMock <IDataAccess>();

            mockDataAccess.Stub(da => da.GetSpecificDrugs(Arg <List <int> > .Is.Anything)).Throw(new ArgumentException());

            var mockThirdPartyAccess = MockRepository.GenerateMock <IThirdPartyDataAccess>();

            var drugService = new DrugService(mockDataAccess, mockThirdPartyAccess);

            // Act
            Action getSpecificDrugs = () => drugService.GetSpecificDrugs(Arg <List <int> > .Is.Anything);

            // Assert
            getSpecificDrugs.ShouldThrow <ArgumentException>();
        }
Beispiel #41
0
        public void Rhino_onDrugRetrieved_WhenEventRaised_HaveDrugsBeenReceivedIsSet()
        {
            // Arrange
            var mockDataAccess       = MockRepository.GenerateMock <IDataAccess>();
            var mockThirdPartyAccess = MockRepository.GenerateMock <IThirdPartyDataAccess>();

            var drugService = new DrugService(mockDataAccess, mockThirdPartyAccess);

            drugService.HaveDrugsBeenReceived.ShouldBeFalse();

            // Act
            // Assert
            mockThirdPartyAccess.Raise(tpa => tpa.OnDrugsRetrievedEvent += null, mockThirdPartyAccess, new DrugsRetrievedArgs {
                HaveDrugsBeenRetrieved = true
            });
            drugService.HaveDrugsBeenReceived.ShouldBeTrue();
        }
        public void GetById_ValidId_ReturnsUser()
        {
            int id = 1;

            var user = new User()
            {
                Id = id
            };

            var userRepository = MockRepository.GenerateMock <IUserRepository>();

            userRepository.Expect(p => p.GetById(id)).Return(user);

            var userService = new UserService(userRepository, null);

            var r = userService.GetById(id);

            Assert.AreEqual(user, r);
            userRepository.VerifyAllExpectations();
        }
        public void Save_ValidUser_Success()
        {
            var user = new User()
            {
                Name  = "John",
                Email = "*****@*****.**"
            };

            var emailValidation = MockRepository.GenerateStub <IEmailValidation>();
            var userRepository  = MockRepository.GenerateMock <IUserRepository>();

            emailValidation.Stub(p => p.isValid(It.IsAny <string>())).Return(true);
            userRepository.Expect(p => p.Save(It.Is <User>(u => u.Equals(user))));

            var userService = new UserService(userRepository, emailValidation);

            userService.Save(user);

            userRepository.VerifyAllExpectations();
        }
        public void Should_invoke_the_isautheticated_and_roles_functions()
        {
            // Arrange
            var context = MockRepository.GenerateMock <ISecurityContext>();

            context.Expect(x => x.CurrenUserAuthenticated()).Return(true).Repeat.Once();
            context.Expect(x => x.CurrenUserRoles()).Return(new List <object> {
                UserRole.Owner
            }.ToArray()).Repeat.Once();
            context.Replay();

            var policyContainer = new PolicyContainer(TestDataFactory.ValidControllerName, TestDataFactory.ValidActionName, TestDataFactory.CreateValidPolicyAppender());

            policyContainer.AddPolicy(new TestPolicy());

            // Act
            policyContainer.EnforcePolicies(context);

            // Assert
            context.VerifyAllExpectations();
        }
        public void Rhino_GetTheDrugs()
        {
            // Arrange
            var mockDataAccess = MockRepository.GenerateMock <IDataAccess>();

            mockDataAccess.Expect(da => da.GetAllTheDrugs()).Return(_fakeDrugList);

            var mockThirdPartyAccess = MockRepository.GenerateMock <IThirdPartyDataAccess>();

            mockThirdPartyAccess.Expect(tpa => tpa.GetThirdPartyDrugInfo(_fakeDrug1)).Return(FakeThirdPartyInfo1);
            mockThirdPartyAccess.Expect(tpa => tpa.GetThirdPartyDrugInfo(_fakeDrug2)).Return(FakeThirdPartyInfo2);
            mockThirdPartyAccess.Expect(tpa => tpa.GetThirdPartyDrugInfo(_fakeDrug3)).Return(FakeThirdPartyInfo3);

            var drugService = new DrugService(mockDataAccess, mockThirdPartyAccess);

            // Act
            var actualDrugs = drugService.GetTheDrugs();

            // Assert
            actualDrugs.Count().ShouldBe(3);

            mockDataAccess.AssertWasCalled(da => da.GetAllTheDrugs(), options => options.Repeat.Times(1));
            mockThirdPartyAccess.AssertWasCalled(da => da.GetThirdPartyDrugInfo(Arg <Drug> .Is.Anything), options => options.Repeat.Times(3));
        }
 public void TestInitialize()
 {
     _mockScheduleRepository  = MockRepository.GenerateMock <IScheduleShiftRepository>();
     _scheduleShiftController = new ScheduleShiftController(_mockScheduleRepository);
 }