public void ConstructingControllerStartsTimelines()
        {
            var checkTimelines = new Mock<ITimer>();
            var updateTimelines = new Mock<ITimer>();
            var queue = new Queue<ITimer>();
            queue.Enqueue(checkTimelines.Object);
            queue.Enqueue(updateTimelines.Object);
            SysTimer.Override = queue.Dequeue;

            var timelines = new Mock<ITimelines>();
            var controller = new TimelineController(timelines.Object);
            controller.StartTimelines();
            checkTimelines.Raise(c => c.Elapsed += null, EventArgs.Empty);
            updateTimelines.Raise(u => u.Elapsed += null, EventArgs.Empty);

            checkTimelines.VerifySet(c => c.Interval = 100);
            checkTimelines.VerifySet(c => c.Interval = 60000);
            checkTimelines.Verify(c => c.Start());
            timelines.Verify(t => t.HomeTimeline());
            timelines.Verify(t => t.MentionsTimeline());

            updateTimelines.VerifySet(u => u.Interval = 30000);
            updateTimelines.Verify(u => u.Start());
            timelines.Verify(t => t.UpdateTimeStamps());
            Assert.That(controller, Is.Not.Null);
        }
        public void should_create_parameters_for_any_parameters_found_in_the_command_text_with_matching_properties_in_the_object()
        {
            // Arrange
            var task = TaskFactory<BuildParametersUsing<MockObject>>.Create();

            var mockDbCommand = new Mock<IDbCommand> { DefaultValue = DefaultValue.Mock };
            var mockDbDataParameter = new Mock<IDbDataParameter>();
            mockDbCommand.Setup(dbCommand => dbCommand.CreateParameter()).Returns(mockDbDataParameter.Object);
            mockDbCommand.Setup(dbCommand => dbCommand.CommandText).Returns("select blah");
            task.CommandWithParameters = mockDbCommand.Object;

            var mockObject = new MockObject { Name = "John Doe", Age = 21 };
            task.ObjectWithValues = mockObject;

            var mockFindParameters = new Mock<FindParametersInCommandText>();
            mockFindParameters.Setup(findParams => findParams.ParameterNames).Returns(new string[] { "@Age" });
            task.FindParametersInCommandText = mockFindParameters.Object;

            // Act
            task.Execute();

            // Assert
            mockDbDataParameter.VerifySet(param => param.ParameterName = "@Age");
            mockDbDataParameter.VerifySet(param => param.Value = 21);
            mockDbCommand.Verify(dbCommand => dbCommand.Parameters.Add(mockDbDataParameter.Object), Times.Once());
        }
        public void it_should_pass_data_to_file_writer()
        {
            // arrange
            var order = new Order {OrderId = 1001, OrderTotal = 10.53M};
            var mockFileWriter = new Mock<IFileWriter>();
            var orderWriter = new OrderWriter(mockFileWriter.Object);

            // act
            orderWriter.WriteOrder(order);

            // assert
            mockFileWriter.Verify(fw => fw.WriteLine("1001,10.53"), Times.Exactly(1));

            // method is not executed, expression tree is veryfied
            mockFileWriter.Verify(fw => fw.WriteLine(It.IsAny<string>()), Times.Once());

            // use regex
            mockFileWriter.Verify(fw => fw.WriteLine(It.IsRegex("^1001")), Times.Once());

            // use predicate
            mockFileWriter.Verify(fw => fw.WriteLine(It.Is<string>(s => s.Length > 3)), Times.Once());
            mockFileWriter.Verify(fw => fw.WriteLine(It.Is<string>(s => s.StartsWith("1001,10.53"))), Times.Once());

            // can use local variable
            string expectedValue = "1001,10.53";
            mockFileWriter.Verify(fw => fw.WriteLine(It.Is<string>(s => s.StartsWith(expectedValue))), Times.Once());

            // verify property
            mockFileWriter.VerifySet(fw => fw.FileName = It.IsAny<string>());
            mockFileWriter.VerifySet(fw => fw.FileName = "1001.txt");
            mockFileWriter.VerifySet(fw => fw.FileName = It.Is<string>(s => s.StartsWith("1001")));
        }
        private void Example()
        {
            var mock = new Mock<IFoo>();

            mock.Verify(foo => foo.Execute("ping"));

            // Verify with custom error message for failure
            mock.Verify(foo => foo.Execute("ping"), "When doing operation X, the service should be pinged always");

            // Method should never be called
            mock.Verify(foo => foo.Execute("ping"), Times.Never());

            // Called at least once
            mock.Verify(foo => foo.Execute("ping"), Times.AtLeastOnce());

            mock.VerifyGet(foo => foo.Name);

            // Verify setter invocation, regardless of value.
            mock.VerifySet(foo => foo.Name);

            // Verify setter called with specific value
            mock.VerifySet(foo => foo.Name = "foo");

            // Verify setter with an argument matcher
            mock.VerifySet(foo => foo.Value = It.IsInRange(1, 5, Range.Inclusive));
        }
        public void GenerateBoard()
        {
            Mock<Grid> grid = new Mock<Grid>();

            grid.SetupAllProperties();

            MainGame game = new MainGame(grid.Object, 200);

            grid.VerifySet(x => x.Width = It.IsAny<double>());
            grid.VerifySet(x => x.Height = It.IsAny<double>());
        }
        public void ForProduction_Should_dissallow_upsert_of_schemas_and_synchronization()
        {
            var settingsFake = new Mock<IDbSettings>();
            var dbFake = new Mock<ISisoDatabase>();
            dbFake.SetupGet(f => f.Settings).Returns(settingsFake.Object);

            dbFake.Object.Configure().ForProduction();

            settingsFake.VerifySet(f => f.AllowUpsertsOfSchemas = false);
            settingsFake.VerifySet(f => f.SynchronizeSchemaChanges = false);
        }
Example #7
0
        public void AuthorizationState_must_define_post_method_and_content_type()
        {
            var mock = new Mock<HttpHelper>("https://www.mystore.com/manager")
                .SetupProperty(m => m.HttpWebRequest.Method);
            mock.Setup(m => m.HttpWebRequest.GetRequestStream()).Returns(new MemoryStream());
            mock.Setup(m => m.HttpWebRequest.GetResponse().GetResponseStream()).Returns(new MemoryStream());

            var target = new APIAuthorizer("client", "key", new Uri("https://www.mystore.com/manager"));
            target.AuthorizationState("code", mock.Object);

            mock.VerifySet(h => h.HttpWebRequest.Method = "POST");
            mock.VerifySet(h => h.HttpWebRequest.ContentType = "application/x-www-form-urlencoded");
        }
        public void Apply_SetsSqlServerConnectionStringWithIntegratedSecurityParameterValuesOnInterface()
        {
            // arrage
            var information = new Mock<IConnectToDatabaseConnectionInformation>();
            var cn = "Server=myServerAddress;Database=myDataBase;Integrated Security=SSPI;";

            // act
            ConnectionStringHelper.Apply(information.Object, cn);

            // assert
            information.VerifySet(x => x.Server = "myServerAddress");
            information.VerifySet(x => x.Database = "myDataBase");
            information.VerifySet(x => x.UseIntegratedSecurity = true);
        }
        public void RedirectWithoutBypassingSecurityWarningIssuesPermanentRedirect()
        {
            // Arrange.
            const string RedirectUrl = "https://www.somewebsite.com/admin/protected-content/";
            var mockResponse = new Mock<HttpResponseBase>();
            var redirector = new LocationRedirector();

            // Act.
            redirector.Redirect(mockResponse.Object, RedirectUrl, false);

            // Assert.
            mockResponse.VerifySet(resp => resp.StatusCode = 301);
            mockResponse.VerifySet(resp => resp.RedirectLocation = RedirectUrl);
            mockResponse.Verify(resp => resp.End());
        }
        public void Apply_SetsSqlServerConnectionStringWithUsernameAndPasswordParameterValuesOnInterface()
        {
            // arrage
            var information = new Mock<IConnectToDatabaseConnectionInformation>();
            var cn = "Data Source=myServerAddress;Initial Catalog=myDataBase;User Id=myUsername;Password=myPassword;";

            // act
            ConnectionStringHelper.Apply(information.Object, cn);

            // assert
            information.VerifySet(x => x.Server = "myServerAddress");
            information.VerifySet(x => x.Database = "myDataBase");
            information.VerifySet(x => x.Username = "myUsername");
            information.VerifySet(x => x.Password = "myPassword");
        }
Example #11
0
        public async Task Given_No_Topic_When_Getting_Then_Topic_List_Returned()
        {
            var mockSubscriptionTrackingService = new Mock<ISubscriptionTrackingService>();
            var topics = new TopicName[] {"topic-1", "topic-2", "topic-3"};
            var controller = new TopicController(mockSubscriptionTrackingService.Object, topics);

            var mockRequest = new Mock<IHttpResourceRequest>();
            var requestUri = new UriBuilder
            {
                Scheme = "http",
                Host = "localhost",
                Path = "/platibus/topic/"
            }.Uri;

            mockRequest.Setup(r => r.HttpMethod).Returns("GET");
            mockRequest.Setup(r => r.Url).Returns(requestUri);

            var mockResponse = new Mock<IHttpResourceResponse>();
            var responseOutputStream = new MemoryStream();
            var responseEncoding = Encoding.UTF8;
            mockResponse.Setup(r => r.ContentEncoding).Returns(responseEncoding);
            mockResponse.Setup(r => r.OutputStream).Returns(responseOutputStream);

            await controller.Process(mockRequest.Object, mockResponse.Object, Enumerable.Empty<string>());

            mockResponse.VerifySet(r => r.StatusCode = 200);
            var responseContent = responseEncoding.GetString(responseOutputStream.GetBuffer());
            var topicsFromResponse = new NewtonsoftJsonSerializer().Deserialize<string[]>(responseContent);

            Assert.That(topicsFromResponse.Length, Is.EqualTo(3));
            Assert.That(topicsFromResponse, Contains.Item("topic-1"));
            Assert.That(topicsFromResponse, Contains.Item("topic-2"));
            Assert.That(topicsFromResponse, Contains.Item("topic-3"));
        }
Example #12
0
        public void DefinitionSetsLexerToIgnoreWhitespace()
        {
            var mockedLexer = new Mock<ILexer>();
            _htmlDefinitions.SetupLexer(mockedLexer.Object);

            mockedLexer.VerifySet(x => x.IgnoreWhitespace = true);
        }
        public void ItDoesNotSetTheSearchStringIfThereIsNotADefaultValue()
        {
            var promptItems = A.ObservableCollection(Mock.Of<ISearchablePromptItem>(), Mock.Of<ISearchablePromptItem>());
            var promptInfo = A.PromptInfo()
                .WithDefaultValues(new ObservableCollection<ValidValue>())
                .Build();

            _promptItemCollectionProvider
                .Setup(
                    b => b.Get(
                        promptInfo.Name,
                        promptInfo.PromptLevelInfo.ParameterName,
                        promptInfo.DefaultValues))
                .Returns(promptItems);

            var promptToReturn = new Mock<IMultiSelectPrompt>();

            _casscadingSearchProvider
                .Setup(p => p.Get(
                    promptInfo.Label, promptInfo.Name,
                    promptInfo.PromptLevelInfo.ParameterName,
                    promptItems,
                    promptItems))
                .Returns(promptToReturn.Object);

            _builder.BuildFrom(promptInfo);

            promptToReturn.VerifySet(p => p.SearchString = It.IsAny<string>(), Times.Exactly(0));
        }
        public void Initialize()
        {
            var context = new Mock<IContextAware>();

            var view = new Mock<INotificationView>();
            {
                view.SetupSet(v => v.Model = It.IsAny<NotificationModel>())
                    .Verifiable();
            }

            var parameter = new NotificationParameter(context.Object);
            var container = new Mock<IDependencyInjectionProxy>();
            {
                container.Setup(c => c.Resolve<IContextAware>())
                    .Returns(context.Object);
                container.Setup(c => c.Resolve<ICollectNotifications>())
                    .Returns(new Mock<ICollectNotifications>().Object);
            }

            var presenter = new NotificationPresenter(container.Object);
            ((IPresenter)presenter).Initialize(view.Object, parameter);

            Assert.AreSame(view.Object, presenter.View);
            Assert.AreSame(parameter, presenter.Parameter);
            view.VerifySet(v => v.Model = It.IsAny<NotificationModel>(), Times.Once());
        }
        public void Initialize()
        {
            var context = new Mock<IContextAware>();

            var view = new Mock<IProjectDescriptionView>();
            {
                view.SetupSet(v => v.Model = It.IsAny<ProjectDescriptionModel>())
                    .Verifiable();
            }

            var parameter = new ProjectDescriptionParameter(context.Object);

            var project = new Mock<IProject>();
            var facade = new ProjectFacade(project.Object);
            var projectLink = new Mock<ILinkToProjects>();
            {
                projectLink.Setup(p => p.ActiveProject())
                    .Returns(facade);
            }

            var container = new Mock<IDependencyInjectionProxy>();
            {
                container.Setup(c => c.Resolve<IContextAware>())
                    .Returns(context.Object);
                container.Setup(c => c.Resolve<ILinkToProjects>())
                    .Returns(projectLink.Object);
            }

            var presenter = new ProjectDescriptionPresenter(container.Object);
            ((IPresenter)presenter).Initialize(view.Object, parameter);

            Assert.AreSame(view.Object, presenter.View);
            Assert.AreSame(parameter, presenter.Parameter);
            view.VerifySet(v => v.Model = It.IsAny<ProjectDescriptionModel>(), Times.Once());
        }
        public void CanGetJavaScriptFiles()
        {
            var handler = new JsHandler(_fileLocationsPaths);

            var mockContext = new Mock<HttpContextBase>();
            var mockRequest = new Mock<HttpRequestBase>();
            var mockResponse = new Mock<HttpResponseBase>();
            var mockCache = new Mock<HttpCachePolicyBase>();

            mockRequest.Setup(x => x["files"]).Returns("test_js_file.js,test_js_file2.js");

            mockResponse.Setup(x => x.Headers).Returns(new System.Collections.Specialized.NameValueCollection());
            mockResponse.Setup(x => x.Cache).Returns(mockCache.Object);

            //there is a problem with this terrible property VaryByParams
            //mockCache.Setup(x => x.VaryByParams).Returns(new HttpCacheVaryByParams());

            mockContext.Setup(x => x.Request).Returns(mockRequest.Object);
            mockContext.Setup(x => x.Response).Returns(mockResponse.Object);

            mockResponse.Setup(x => x.Write(It.IsAny<string>()))
                .Callback<string>(x =>
                {
                    Assert.IsNotNullOrEmpty(x, "Merged file content is empty");
                });

            handler.ProcessRequest(mockContext.Object);

            mockResponse.VerifySet(x => x.ContentType, "Content type should be set at least once");
            mockResponse.Verify(x => x.Write(It.IsAny<string>()), "Write method should be called at least once");
        }
        public async Task WriteAsync_DoesNotWriteNullStrings()
        {
            // Arrange
            Encoding encoding = Encoding.UTF8;
            var memoryStream = new MemoryStream();
            var response = new Mock<HttpResponse>();
            response.SetupProperty<long?>(o => o.ContentLength);
            response.SetupGet(r => r.Body).Returns(memoryStream);
            var httpContext = new Mock<HttpContext>();
            httpContext.Setup(o => o.Response).Returns(response.Object);

            var formatter = new StringOutputFormatter();
            var context = new OutputFormatterWriteContext(
                httpContext.Object,
                new TestHttpResponseStreamWriterFactory().CreateWriter,
                typeof(string),
                @object: null);

            // Act
            await formatter.WriteResponseBodyAsync(context);

            // Assert
            Assert.Equal(0, memoryStream.Length);
            response.VerifySet(r => r.ContentLength = It.IsAny<long?>(), Times.Never());
        }
Example #18
0
        public void HtmlTokenDefinitionsPassedToLexer()
        {
            var mockedLexer = new Mock<ILexer>();
            _htmlDefinitions.SetupLexer(mockedLexer.Object);

            mockedLexer.VerifySet(x => x.TokenDefinitions = It.IsAny<TokenDefinition[]>());
        }
 public void should_have_a_http_post_method()
 {
     var mock = new Mock<ICloudFilesRequest>();
     mock.SetupGet(x => x.Headers).Returns(new WebHeaderCollection());
     setPublicContainerDetails.Apply(mock.Object);
     mock.VerifySet(x => x.Method = "POST");
 }
        public async Task WriteAsync_DoesNotWriteNullStrings()
        {
            // Arrange
            Encoding encoding = Encoding.UTF8;
            var memoryStream = new MemoryStream();
            var response = new Mock<HttpResponse>();
            response.SetupProperty<long?>(o => o.ContentLength);
            response.SetupGet(r => r.Body).Returns(memoryStream);
            var mockHttpContext = new Mock<HttpContext>();
            mockHttpContext.Setup(o => o.Response).Returns(response.Object);

            var formatter = new StringOutputFormatter();
            var formatterContext = new OutputFormatterContext()
            {
                Object = null,
                DeclaredType = typeof(string),
                HttpContext = mockHttpContext.Object,
                SelectedEncoding = encoding
            };

            // Act
            await formatter.WriteResponseBodyAsync(formatterContext);

            // Assert
            Assert.Equal(0, memoryStream.Length);
            response.VerifySet(r => r.ContentLength = It.IsAny<long?>(), Times.Never());
        }
Example #21
0
        public void Call_with_HttpMethod_Post_must_write_content_on_request_body()
        {
            var content =   "{" +
                                "\"id\": \"1\"," +
                                "\"name\": \"Department\"" +
                            "}";

            string writedString = string.Empty;
            var mockMS = new Mock<MemoryStream>();
            mockMS.Setup(m => m.CanWrite).Returns(true);
            mockMS.Setup(m => m.Write(It.IsAny<byte[]>(), It.IsAny<int>(), It.IsAny<int>())).Callback(
                (byte[] b, int i1, int i2) =>
                {
                    writedString = new System.Text.ASCIIEncoding().GetString(b, i1, i2);
                });

            var mock = new Mock<HttpHelper>("https://www.mystore.com/api/v1");
            mock.SetupProperty(m => m.HttpWebRequest.Method);
            mock.SetupProperty(m => m.HttpWebRequest.ContentType);
            mock.SetupProperty(m => m.HttpWebRequest.Headers, new WebHeaderCollection());
            mock.Setup(m => m.HttpWebRequest.GetRequestStream()).Returns(mockMS.Object);
            mock.Setup(m => m.HttpWebRequest.GetResponse().GetResponseStream()).Returns(new MemoryStream());

            APIClient target = new APIClient(new AuthState
            {
                AccessToken = "token",
                ApiUrl = "https://www.mystore.com/api/v1"
            });

            target.Call(HttpMethods.POST, "departments", content, mock.Object);

            mock.VerifySet(h => h.HttpWebRequest.Method = "POST");
            Assert.AreEqual(content, writedString);
        }
        public void TestConstructor()
        {
            //Test on defaults of port 25 and
            var mock = new Mock<SMTP.ISmtpClient>();
            mock.SetupProperty(foo => foo.EnableSsl);
            var client = mock.Object;
            var credentials = new NetworkCredential("username", "password");
            SMTP.GetInstance(client, credentials);
            mock.Verify(foo => foo.EnableSsl, Times.Never());

            mock = new Mock<SMTP.ISmtpClient>();
            mock.SetupProperty(foo => foo.EnableSsl);
            client = mock.Object;
            credentials = new NetworkCredential("username", "password");
            SMTP.GetInstance(client, credentials, port:SMTP.SslPort);
            mock.VerifySet(foo => foo.EnableSsl = true);

            mock = new Mock<SMTP.ISmtpClient>();
            mock.SetupProperty(foo => foo.EnableSsl);
            client = mock.Object;
            credentials = new NetworkCredential("username", "password");
            try
            {
                SMTP.GetInstance(client, credentials, port: SMTP.TlsPort);
                Assert.Fail("should have thrown an unsupported port exception");
            }
            catch (NotSupportedException ex)
            {
                Assert.AreEqual("TLS not supported", ex.Message);
            }
        }
Example #23
0
        public async Task Given_No_Topic_When_Posting_Then_400_Returned()
        {
            var mockSubscriptionTrackingService = new Mock<ISubscriptionTrackingService>();
            var topics = new TopicName[] {"topic-1", "topic-2", "topic-3"};
            var controller = new TopicController(mockSubscriptionTrackingService.Object, topics);

            var mockRequest = new Mock<IHttpResourceRequest>();
            var requestUri = new UriBuilder
            {
                Scheme = "http",
                Host = "localhost",
                Path = "/platibus/topic/"
            }.Uri;
            mockRequest.Setup(r => r.HttpMethod).Returns("POST");
            mockRequest.Setup(r => r.Url).Returns(requestUri);

            var mockResponse = new Mock<IHttpResourceResponse>();
            var responseOutputStream = new MemoryStream();
            var responseEncoding = Encoding.UTF8;
            mockResponse.Setup(r => r.ContentEncoding).Returns(responseEncoding);
            mockResponse.Setup(r => r.OutputStream).Returns(responseOutputStream);

            await controller.Process(mockRequest.Object, mockResponse.Object, Enumerable.Empty<string>());

            mockResponse.VerifySet(r => r.StatusCode = 400);
        }
        public void ConnectRequestCallsReceiveOnConnectionThenSend()
        {
            var context = new Mock<HttpContextBase>();
            var request = new Mock<HttpRequestBase>();
            var response = new Mock<HttpResponseBase>();
            request.Setup(m => m.Path).Returns("/foo/connect");
            request.Setup(m => m["clientId"]).Returns("1");
            context.Setup(m => m.Response).Returns(response.Object);
            context.Setup(m => m.Request).Returns(request.Object);
            var json = new Mock<IJsonStringifier>();
            var heartBeat = new Mock<ITransportHeartBeat>();
            var transport = new Mock<LongPollingTransport>(context.Object, json.Object, heartBeat.Object) { CallBase = true };
            var connection = new Mock<IConnection>();
            PersistentResponse persistentResponse = null;
            connection.Setup(m => m.ReceiveAsync()).Returns(TaskAsyncHelper.FromResult<PersistentResponse>(persistentResponse));

            transport.Object.ProcessRequest(connection.Object)().Wait();

            heartBeat.Verify(m => m.AddConnection(transport.Object), Times.Once());
            connection.Verify(m => m.ReceiveAsync(), Times.Once());
            transport.Verify(m => m.Send(persistentResponse), Times.Once());
            response.VerifySet(m => m.ContentType = "application/json");
            response.Verify(m => m.Write(It.IsAny<string>()), Times.Once());
            json.Verify(m => m.Stringify(persistentResponse), Times.Once());
        }
        public void Initialize()
        {
            var context = new Mock<IContextAware>();

            var view = new Mock<IFeedbackView>();
            {
                view.SetupSet(v => v.Model = It.IsAny<FeedbackModel>())
                    .Verifiable();
            }

            var parameter = new FeedbackParameter(context.Object);

            var container = new Mock<IDependencyInjectionProxy>();
            {
                container.Setup(c => c.Resolve<IContextAware>())
                    .Returns(context.Object);
                container.Setup(c => c.Resolve<SendFeedbackReportCommand>())
                    .Returns(new SendFeedbackReportCommand(new Mock<ISendFeedbackReports>().Object));
                container.Setup(c => c.Resolve<IBuildReports>())
                    .Returns(new Mock<IBuildReports>().Object);
            }

            var presenter = new FeedbackPresenter(container.Object);
            ((IPresenter)presenter).Initialize(view.Object, parameter);

            Assert.AreSame(view.Object, presenter.View);
            Assert.AreSame(parameter, presenter.Parameter);
            view.VerifySet(v => v.Model = It.IsAny<FeedbackModel>(), Times.Once());
        }
        public void Initialize()
        {
            var context = new Mock<IContextAware>();

            var view = new Mock<IProjectView>();
            {
                view.SetupSet(v => v.Model = It.IsAny<ProjectModel>())
                    .Verifiable();
            }

            var parameter = new ProjectParameter(context.Object);

            var projectLink = new Mock<ILinkToProjects>();
            Func<string, IDisposable> func = s => new MockDisposable();

            var command = new CloseProjectCommand(projectLink.Object, func);
            var container = new Mock<IDependencyInjectionProxy>();
            {
                container.Setup(c => c.Resolve<IContextAware>())
                    .Returns(context.Object);
                container.Setup(c => c.Resolve<CloseProjectCommand>())
                    .Returns(command);
            }

            var presenter = new ProjectPresenter(container.Object);
            ((IPresenter)presenter).Initialize(view.Object, parameter);

            Assert.AreSame(view.Object, presenter.View);
            Assert.AreSame(parameter, presenter.Parameter);
            view.VerifySet(v => v.Model = It.IsAny<ProjectModel>(), Times.Once());
        }
        public void Example()
        {
            var mock = new Mock<IFoo>();

            mock.Setup(foo => foo.Name).Returns("bar");

            // auto-mocking hierarchies (a.k.a. recursive mocks)
            mock.Setup(foo => foo.Bar.Baz.Name).Returns("baz");

            // expects an invocation to set the value to "foo"
            mock.SetupSet(foo => foo.Name = "foo");

            // or verify the setter directly
            mock.VerifySet(foo => foo.Name = "foo");

            //Setup a property so that it will automatically start tracking its value (also known as Stub):
            // start "tracking" sets/gets to this property
            mock.SetupProperty(f => f.Name);

            // alternatively, provide a default value for the stubbed property
            mock.SetupProperty(f => f.Name, "foo");

            // Now you can do:
            IFoo ifoo = mock.Object;
            // Initial value was stored
            Assert.AreEqual("foo", ifoo.Name);

            // New value set which changes the initial value
            ifoo.Name = "bar";
            Assert.AreEqual("bar", ifoo.Name);
        }
        public void MissingHttpStatusText()
        {
            bool isInvoked = false;

            string badHeader = "HTTP/1.1 200\r\nContent-Length: 35\r\nConnection: close\r\nContent-Type: image/gif\r\n\r\n";
            byte[] badHeaderData = Encoding.UTF8.GetBytes( badHeader );

            Mock<IHttpStreamParserContext> mockContext = new Mock<IHttpStreamParserContext>();
            mockContext.Setup(m => m.OnReadResponseHeaderComplete("1.1", It.IsAny<IHttpHeaders>(), 200, ""))
                .Callback<string, IHttpHeaders, int, string>(
                    (s, h, si, st) =>
                    {
                        isInvoked = true;
                        Assert.That(h.Count, Is.EqualTo(3));
                        Assert.That(h["connection"], Is.EqualTo("close"));
                    });

            ReadHeaderState headerState = new ReadHeaderState( mockContext.Object );

            headerState.AcceptData( badHeaderData );

            mockContext.VerifySet(m => m.State = It.IsAny<ReadNormalBodyState>());

            Assert.IsTrue(isInvoked);
        }
        public void ValidRequestText()
        {
            bool isInvoked = false;

            string header = "GET / HTTP/1.1\r\nHost: www.yahoo.com\r\n\r\n";
            byte[] headerData = Encoding.UTF8.GetBytes(header);

            Mock<IHttpStreamParserContext> mockContext = new Mock<IHttpStreamParserContext>();
            mockContext.Setup(m => m.OnReadRequestHeaderComplete("1.1", It.IsAny<IHttpHeaders>(), "GET", "/"))
                .Callback<string, IHttpHeaders, string, string>(
                    (s, h, si, st) =>
                    {
                        isInvoked = true;
                        Assert.That(h.Count, Is.EqualTo(1));
                        Assert.That(h["host"], Is.EqualTo("www.yahoo.com"));
                    });

            ReadHeaderState headerState = new ReadHeaderState(mockContext.Object);

            headerState.AcceptData(headerData);

            mockContext.VerifySet(m => m.State = It.IsAny<ReadHeaderState>());

            Assert.IsTrue(isInvoked);
        }
 public void should_have_a_http_post_method()
 {
     var mock = new Mock<ICloudFilesRequest>();
     var headers = new WebHeaderCollection();
     mock.SetupGet(x => x.Headers).Returns(headers);
     setStorageItemInformation.Apply(mock.Object);
     mock.VerifySet(x=>x.Method="POST");
 }