public Mock<IAsyncCloudGateway> InitializeGetChildItemsAsyncWithFilter(RootName rootName, string path, string filter, params IEnumerable<FileSystemInfoContract>[] pathChildItems)
        {
            var gatewayMock = new Mock<IAsyncCloudGateway>(MockBehavior.Strict);
            gatewayMock.SetupSequence(g => g.GetRootAsync(rootName, FileSystemFixture.ApiKey))
                .ReturnsAsync(FileSystemFixture.Root)
                .ThrowsAsync(new InvalidOperationException("Redundant call to GetRoot()"));
            gatewayMock.SetupSequence(g => g.GetDriveAsync(rootName, FileSystemFixture.ApiKey))
                .ReturnsAsync(FileSystemFixture.Drive)
                .Throws(new InvalidOperationException("Redundant call to GetDrive()"));

            if (path != null) {
                path = path + Path.DirectorySeparatorChar;
                for (int i = 0, j = 0; i >= 0; i = path.IndexOf(Path.DirectorySeparatorChar, Math.Min(path.Length, i + 2)), ++j) {
                    var currentPath = new DirectoryId(path.Substring(0, Math.Max(1, i)));

                    bool applyFilter = j == pathChildItems.Length - 1;
                    var effectiveFilter = applyFilter && filter != null ? new Regex("^" + filter.Replace("*", ".*") + "$") : null;
                    gatewayMock.SetupSequence(g => g.GetChildItemAsync(rootName, currentPath))
                        .ReturnsAsync(applyFilter ? pathChildItems[j].Where(f => effectiveFilter == null || effectiveFilter.IsMatch(f.Name)) : pathChildItems[j])
                        .ThrowsAsync(new InvalidOperationException(string.Format(CultureInfo.CurrentCulture, "Redundant access to {0}", currentPath)));
                }
            }

            return gatewayMock;
        }
Example #2
0
        public void setUpBeforeEachTest()
        {
            litle = new litleRequest();

            mockXmlReader = new Mock<XmlReader>();
            mockXmlReader.SetupSequence(XmlReader => XmlReader.ReadToFollowing(It.IsAny<String>())).Returns(true).Returns(true).Returns(false);
            mockXmlReader.SetupSequence(XmlReader => XmlReader.ReadState).Returns(ReadState.Initial).Returns(ReadState.Interactive).Returns(ReadState.Closed);
        }
        public async void GetWeatherAsync_2ClientsWithOneClientWrong()
        {
            var mockHttpClient = new Mock<IHttpClient>();

            //Arrange 
            mockHttpClient.SetupSequence(x => x.GetStringAsync(It.IsAny<string>()))
            //BBC
            .Returns(Task.Run<HttpClientResponse>(() => DataTest.HttpClientResponse["BBCWeatherOK"]))
            //AccuWeather
            .Returns(Task.Run<HttpClientResponse>(() => DataTest.HttpClientResponse["Wrong"]));


            var moclHttpClientFactory = new Mock<IHttpClientFactory>();
            moclHttpClientFactory.Setup(x => x.GetHttpClient<HttpClientWrapper>()).Returns(mockHttpClient.Object);

            _container.RegisterInstance<IHttpClientFactory>(moclHttpClientFactory.Object);

            var manager = _container.Resolve<ApiWeatherManager>();

            //Act
            var result = await manager.GetWeatherAsync("anylocation", Api.Weather.TemperatureUnits.Farenheits, Api.Weather.WindUnits.MPHs);

            //Assert
            result.WindUnit.Should().Be(WindUnits.MPHs);
            result.TemperatureUnit.Should().Be(TemperatureUnits.Farenheits);
            result.Wind.Should().Be(0.62f);
            result.Temperature.Should().Be(77);
        }
        public void Main_WithTwoValidCommands_ExitsProgramWhenEmptyStringIsEntered()
        {
            // Arrange
            Mock<IStringCalculator> mockCalculator = new Mock<IStringCalculator>();
            Mock<IConsole> mockConsole = new Mock<IConsole>();
            mockCalculator.Setup(c => c.Add("1,2,3")).Returns(6);
            mockCalculator.Setup(c => c.Add("3")).Returns(3);
            mockCalculator.Setup(c => c.Add("5")).Returns(5);

            mockConsole.SetupSequence(c => c.ReadLine())
                .Returns("3")
                .Returns("5")
                .Returns("");

            StringCalculatorConsole stringCalculatorConsole = CreateCalcConsole(mockCalculator, mockConsole);

            // Act
            stringCalculatorConsole.Main(new string[] { "scalc '1,2,3'" });

            // Assert
            mockConsole.Verify(c => c.WriteLine("The result is 6"));
            mockConsole.Verify(c => c.WriteLine("another input please"), Times.Exactly(3));
            mockConsole.Verify(c => c.WriteLine("The result is 3"));
            mockConsole.Verify(c => c.WriteLine("The result is 5"));
            mockConsole.Verify(c => c.ReadLine(), Times.Exactly(3));
        }
Example #5
0
        public async Task WriteFileAsync_WritesResponse_InChunksOfFourKilobytes()
        {
            // Arrange
            var mockReadStream = new Mock<Stream>();
            mockReadStream.SetupSequence(s => s.ReadAsync(It.IsAny<byte[]>(), 0, 0x1000, CancellationToken.None))
                .Returns(Task.FromResult(0x1000))
                .Returns(Task.FromResult(0x500))
                .Returns(Task.FromResult(0));

            var mockBodyStream = new Mock<Stream>();
            mockBodyStream
                .Setup(s => s.WriteAsync(It.IsAny<byte[]>(), 0, 0x1000, CancellationToken.None))
                .Returns(Task.FromResult(0));

            mockBodyStream
                .Setup(s => s.WriteAsync(It.IsAny<byte[]>(), 0, 0x500, CancellationToken.None))
                .Returns(Task.FromResult(0));

            var result = new FileStreamResult(mockReadStream.Object, "text/plain");

            var httpContext = GetHttpContext();
            httpContext.Response.Body = mockBodyStream.Object;

            var actionContext = new ActionContext(httpContext, new RouteData(), new ActionDescriptor());

            // Act
            await result.ExecuteResultAsync(actionContext);

            // Assert
            mockReadStream.Verify();
            mockBodyStream.Verify();
        }
        public void SerializeError_serializes_httperror()
        {
            using (var stream = new MemoryStream())
            {
                var textWriter = new StreamWriter(stream);
                var writer = new JsonTextWriter(textWriter);

                var mockInnerException = new Mock<Exception>(MockBehavior.Strict);
                mockInnerException.Setup(m => m.Message).Returns("Inner exception message");
                mockInnerException.Setup(m => m.StackTrace).Returns("Inner stack trace");

                var outerException = new Exception("Outer exception message", mockInnerException.Object);

                var error = new HttpError(outerException, true)
                {
                    StackTrace = "Outer stack trace"
                };
                var jsonSerializer = new JsonSerializer();

                var mockIdProvider = new Mock<IErrorIdProvider>(MockBehavior.Strict);
                mockIdProvider.SetupSequence(p => p.GenerateId(It.IsAny<HttpError>())).Returns("OUTER-ID").Returns("INNER-ID");

                var serializer = new ErrorSerializer(mockIdProvider.Object);
                serializer.SerializeError(error, stream, writer, jsonSerializer);

                writer.Flush();

                var expectedJson = File.ReadAllText("ErrorSerializerTest.json");
                var minifiedExpectedJson = JsonHelpers.MinifyJson(expectedJson);
                var output = System.Text.Encoding.ASCII.GetString(stream.ToArray());
                output.Should().Be(minifiedExpectedJson);
            }
        }
Example #7
0
        public void DisposeDisposesAllEngines()
        {
            var engines = new[]
            {
                new Mock<IJsEngine>(),
                new Mock<IJsEngine>(),
                new Mock<IJsEngine>(),
                new Mock<IJsEngine>(),
            };
            var factory = new Mock<IEngineFactoryForMock>();
            factory.SetupSequence(x => x.EngineFactory())
                .Returns(engines[0].Object)
                .Returns(engines[1].Object)
                .Returns(engines[2].Object)
                .Returns(engines[3].Object);
            var config = new JsPoolConfig
            {
                StartEngines = 3,
                EngineFactory = factory.Object.EngineFactory
            };

            var pool = new JsPool(config);
            pool.Dispose();

            foreach (var engine in engines)
            {
                engine.Verify(x => x.Dispose());
            }
        }
        public void IntegrationTestProcessBatch()
        {
            var orders = new List<IDummyOrderObject>();
            for (var i = 0; i < 6; i++)
            {
                var order = new Mock<IDummyOrderObject>();
                order.Setup(s => s.OrderNumber).Returns(i.ToString(CultureInfo.InvariantCulture));
                orders.Add(order.Object);
            }

            var repo = new Mock<IFraudRepository>();
            var mockRuleFailing = RuleGenerators.FetchMockedRule(true);
            var mockRulePassing = RuleGenerators.FetchMockedRule(false);
            repo
                .SetupSequence(m => m.FetchAllRules())
                .Returns(new List<IFraudRule> { mockRuleFailing.Object })
                .Returns(new List<IFraudRule> { mockRulePassing.Object })
                .Returns(new List<IFraudRule> { mockRuleFailing.Object })
                .Returns(new List<IFraudRule> { mockRulePassing.Object })
                .Returns(new List<IFraudRule> { mockRuleFailing.Object })
                .Returns(new List<IFraudRule> { mockRulePassing.Object });

            var bulkProcessor = new FraudCheckerBulkProcessor(repo.Object);
            var report = bulkProcessor.ProcessBatch(orders);

            Assert.AreEqual(6, report.Count);
            Assert.IsFalse(report["0"].OverallResult);
            Assert.IsTrue(report["1"].OverallResult);
            Assert.IsFalse(report["2"].OverallResult);
            Assert.IsTrue(report["3"].OverallResult);
            Assert.IsFalse(report["4"].OverallResult);
            Assert.IsTrue(report["5"].OverallResult);
        }
        public void SwagOMeterViewModelShouldAwardSwagAndCanSwagSetToFalseWhenSwagAndAttendeesAreAllUsedUpAfterAward()
        {
            // Arrange
            var mockAttendee = new Mock<IAttendee>();
            mockAttendee.SetupGet(a => a.Name).Returns("Bob");

            var mockSwag = new Mock<ISwag>();
            mockSwag.SetupGet(s => s.Company).Returns("Company");
            mockSwag.SetupGet(s => s.Thing).Returns("Thing");

            var stubAttendeeSource = new Mock<IAttendeeSource>();

            var stubSwagSource = new Mock<ISwagSource>();

            var stubWinnersSource = new Mock<IWinnersSource>();

            var stubSwagOMeterEngine = new Mock<ISwagOMeterAwardEngine>();
            stubSwagOMeterEngine.Setup(e => e.CheckCanSwag()).Returns(true);
            stubSwagOMeterEngine.SetupSequence(e => e.CanSwag).Returns(true).Returns(false);
            stubSwagOMeterEngine.SetupGet(e => e.AwardedSwag).Returns(mockSwag.Object);
            stubSwagOMeterEngine.SetupGet(e => e.WinningAttendee).Returns(mockAttendee.Object);

            // Act
            var viewModel = new SwagOMeterViewModel(stubAttendeeSource.Object, stubSwagSource.Object, stubWinnersSource.Object, stubSwagOMeterEngine.Object);
            viewModel.ViewReady();
            viewModel.AwardSwagCommand.Execute(null);

            // Assert
            StringAssert.Matches(viewModel.WinningAttendee, new Regex("Bob"));
            StringAssert.Matches(viewModel.WonSwag, new Regex("Company Thing"));
            Assert.IsFalse(viewModel.CanSwag);
        }
Example #10
0
		public void GetEngineReturnsAllAvailableEngines()
		{
			var engines = new[]
			{
				new Mock<IJsEngine>().Object,
				new Mock<IJsEngine>().Object,
				new Mock<IJsEngine>().Object,
			};
			var factory = new Mock<IEngineFactoryForMock>();
			factory.SetupSequence(x => x.EngineFactory())
				// Initial call to factory is to determine engine type, we don't care
				// about that here.
				.Returns(new Mock<IJsEngine>().Object)
				.Returns(engines[0])
				.Returns(engines[1])
				.Returns(engines[2]);
			var config = new JsPoolConfig
			{
				StartEngines = 3,
				EngineFactory = factory.Object.EngineFactory
			};

			var pool = new JsPool(config);
			var resultEngines = new[]
			{
				pool.GetEngine(),
				pool.GetEngine(),
				pool.GetEngine(),
			};

			CollectionAssert.AreEquivalent(engines, resultEngines);
		}
        public void ThenIfOneResourceFailsToUploadThenAllAreReloaded()
        {
            // Arrange: unsuccessful resource upload followed by two successful uploads
            var ckanApi = new Mock<ICkanApi>(MockBehavior.Strict);
            ckanApi.Setup(x => x.CreateResource(resource1)).Returns(resource1);
            ckanApi.SetupSequence(x => x.CreateResource(resource2))
                .Throws<CkanTimeoutException>()
                .Throws<CkanInternalServerException>()
                .Returns(resource2);

            // Arrange: package update after failed resource upload
            package.Resources.Add(resource1);
            ckanApi.Setup(x => x.GetPackage(packageId)).Returns(package);
            ckanApi.Setup(x => x.UpdatePackage(package)).Returns(package);

            // Act: upload resources
            var resources = UploadResources(ckanApi);

            // Assert: expected number of resources
            Assert.AreEqual(2, resources.Count);

            // Assert: package resources have been cleared
            Assert.AreEqual(0, package.Resources.Count);
            ckanApi.VerifyAll();
        }
		public void GetControllersMetaData_LocalControllers_GetWithoutIgnoredAndSortedCorrectly()
		{
			// Assign

			SimplifyWebTypesFinder.ExcludedAssembliesPrefixes.Remove("Simplify");
			SimplifyWebTypesFinder.ExcludedAssembliesPrefixes.Add("DynamicProxyGenAssembly2");
			SimplifyWebTypesFinder.CleanLoadedTypesAndAssembliesInfo();

			var factory = new Mock<IControllerMetaDataFactory>();
			var store = new ControllersMetaStore(factory.Object);

			factory.SetupSequence(x => x.CreateControllerMetaData(It.IsAny<Type>()))
				.Returns(new ControllerMetaData(typeof(TestController1), new ControllerExecParameters(null, 2)))
				.Returns(new ControllerMetaData(typeof(TestController2), new ControllerExecParameters(null, 1)))
				.Returns(new ControllerMetaData(typeof(TestController4)))
				.Returns(new ControllerMetaData(typeof(TestController5)));

			// Act
			var metaData = store.ControllersMetaData;

			Assert.AreEqual(4, metaData.Count);
			Assert.AreEqual("TestController4", metaData[0].ControllerType.Name);
			Assert.AreEqual("TestController5", metaData[1].ControllerType.Name);
			Assert.AreEqual("TestController2", metaData[2].ControllerType.Name);
			Assert.AreEqual("TestController1", metaData[3].ControllerType.Name);

			factory.Verify(x => x.CreateControllerMetaData(It.Is<Type>(t => t == typeof(TestController1))));
			factory.Verify(x => x.CreateControllerMetaData(It.Is<Type>(t => t == typeof(TestController2))));
			factory.Verify(x => x.CreateControllerMetaData(It.Is<Type>(t => t == typeof(TestController4))));
			factory.Verify(x => x.CreateControllerMetaData(It.Is<Type>(t => t == typeof(TestController5))));
		}
        public void setUpBeforeEachTest()
        {
            _mockConfig = new Dictionary<string, string>();
            _mockConfig["url"] = "https://www.mockurl.com";
            _mockConfig["reportGroup"] = "Mock Report Group";
            _mockConfig["username"] = "mockUser";
            _mockConfig["printxml"] = "false";
            _mockConfig["timeout"] = "35";
            _mockConfig["proxyHost"] = "www.mockproxy.com";
            _mockConfig["merchantId"] = "MOCKID";
            _mockConfig["password"] = "mockPassword";
            _mockConfig["proxyPort"] = "3000";
            _mockConfig["sftpUrl"] = "www.mockftp.com";
            _mockConfig["sftpUsername"] = "mockFtpUser";
            _mockConfig["sftpPassword"] = "mockFtpPassword";
            _mockConfig["knownHostsFile"] = "C:\\MockKnownHostsFile";
            _mockConfig["onlineBatchUrl"] = "www.mockbatch.com";
            _mockConfig["onlineBatchPort"] = "4000";
            _mockConfig["requestDirectory"] = "C:\\MockRequests";
            _mockConfig["responseDirectory"] = "C:\\MockResponses";

            _mockCache.Setup(x => x[_mockConfig["responseDirectory"] + "\\Responses\\" + mockFileName])
                .Returns(new StringBuilder());
            litle = new litleRequest(_mockCache.Object, _mockConfig);

            mockXmlReader = new Mock<XmlReader>();
            mockXmlReader.SetupSequence(XmlReader => XmlReader.ReadToFollowing(It.IsAny<string>()))
                .Returns(true)
                .Returns(true)
                .Returns(false);
            mockXmlReader.SetupSequence(XmlReader => XmlReader.ReadState)
                .Returns(ReadState.Initial)
                .Returns(ReadState.Interactive)
                .Returns(ReadState.Closed);
        }
        public async Task CallAsync_MethodWithReturnValue()
        {
            var mockService = new Mock<ITestService>();
            mockService
                .SetupSequence(m => m.TestMethod("good"))
                .Returns("BAD")
                .Returns("OK");

            mockService.Setup(m => m.TestMethod("second", "two")).Returns("2");

            var serviceHost = InProcTestFactory.CreateHost<ITestService>(new TestServiceImpl(mockService));

            var proxy = WcfClientProxy.CreateAsyncProxy<ITestService>(c =>
            {
                c.MaximumRetries(1);
                c.SetEndpoint(serviceHost.Binding, serviceHost.EndpointAddress);
                c.RetryOnResponse<string>(s => s == "BAD");
            });

            Console.WriteLine("Caller thread: " + Thread.CurrentThread.ManagedThreadId);

            string result = await proxy.CallAsync(m => m.TestMethod("good"));
            string result2 = await proxy.CallAsync(m => m.TestMethod("second", "two"));

            Console.WriteLine("Continuation thread: " + Thread.CurrentThread.ManagedThreadId);

            Assert.That(result, Is.EqualTo("OK"));
            Assert.That(result2, Is.EqualTo("2"));
        }
        public void SetUp()
        {
            _archetype = ContentHelpers.Archetype;

            var content = ContentHelpers.FakeContent(123, "Fake Node 1", properties: new Collection<IPublishedProperty>
            {
                new FakePublishedProperty("myArchetypeProperty", _archetype, true)
            });

            _content = new FakeModel(content);
            _propertyDescriptor = TypeDescriptor.GetProperties(_content)["TextString"];

            _context = new FakeDittoValueResolverContext(_content, _propertyDescriptor);

            var mockedPropertyService = new Mock<PropertyValueService>();

            mockedPropertyService.SetupSequence(
                i =>
                    i.Set(It.IsAny<IPublishedContent>(), It.IsAny<CultureInfo>(), It.IsAny<PropertyInfo>(),
                        It.IsAny<object>(), It.IsAny<object>(), It.IsAny<DittoValueResolverContext>()))
                        .Returns(new HtmlString("<p>This is the <strong>summary</strong> text.</p>"))
                        .Returns("Ready to Enroll?")
                        .Returns("{}");

            _sut = new ArchetypeBindingService(mockedPropertyService.Object, new DittoAliasLocator());
        }
Example #16
0
 public void Setup()
 {
     _display = new Mock<IGameDisplay>();
     _display.SetupSequence<IGameDisplay, bool>(x => x.PlayAgainMessage()).Returns(true).Returns(true).Returns(false);
     _board = new Mock<IBoard>();
     _playGameHandler = new Mock<PlayGameHandler>();
     _gameEngine = new GameEngine(_display.Object, _board.Object, _playGameHandler.Object);
 }
Example #17
0
        public void Setup()
        {
            Mock<ILoggerService> loggerService = new Mock<ILoggerService>();
            loggerService.SetupSequence(o => o.Log(It.IsAny<Log>())).Returns(true);

            FileService Service = new FileService(loggerService.Object);
            Service.SaveMedia(StoredMedia, data);
        }
Example #18
0
        public void DeleteMedia_NormalCase_Deleted()
        {
            Mock<ILoggerService> loggerService = new Mock<ILoggerService>();
            loggerService.SetupSequence(o => o.Log(It.IsAny<Log>())).Returns(true);

            FileService Service = new FileService(loggerService.Object);
            bool flag = Service.DeleteMedia(this.StoredMedia);
            Assert.IsTrue(flag);
        }
Example #19
0
        public void GetLogs_LogsNotExist_ReturnsNullList()
        {
            Mock<IRepository<Log>> repository = new Mock<IRepository<Log>>();
            repository.SetupSequence(o => o.GetAll()).Returns(null);

            LoggerService service = new LoggerService(repository.Object);
            IList<Log> logs = service.GetLogs();
            Assert.IsNull(logs);
        }
Example #20
0
        public void SetUp()
        {
            adapter = new Mock<IShaderAdapter>();
            adapter.SetupSequence(a => a.CreateProgram())
                   .Returns(1)
                   .Returns(2);
            adapter.SetupSequence(a => a.CreateShader(It.IsAny<ShaderType>()))
                   .Returns(1)
                   .Returns(2);
            adapter.Setup(a => a.GetShaderProgramStatus(
                    It.IsAny<int>(), GetProgramParameterName.LinkStatus))
                   .Returns(true);

            vertexShader = new Shader(adapter.Object, ShaderType.VertexShader);
            fragmentShader = new Shader(adapter.Object, ShaderType.FragmentShader);

            program = new ShaderProgram(adapter.Object, vertexShader, fragmentShader);
        }
        public void SendMailsTest()
        {
            //Arrange
            var emailBuilder1 = new Mock<IEmailBuilder>();
            var emailBuilder2 = new Mock<IEmailBuilder>();
            var mailClient1 = new Mock<IMailClient>();
            var mailClient2 = new Mock<IMailClient>();
            var mailFactory = new Mock<IEmailFactory>();
            var mailIntialezer = new Mock<IEmailInitializer>();

            mailFactory.SetupSequence(m => m.CreateEmailBuilder())
                       .Returns(emailBuilder1.Object)
                       .Returns(emailBuilder2.Object);

            mailFactory.SetupSequence(m => m.CreateMailClient())
                       .Returns(mailClient1.Object)
                       .Returns(mailClient2.Object);
            
            var emailList = new List<EmailBase>() { new Mock<EmailBase>().Object, new Mock<EmailBase>().Object };
            var repository = new MailerRepository(mailFactory.Object, mailIntialezer.Object);

            mailClient1.Setup(m => m.Send(It.IsAny<IEmailBuilder>())).Returns(() =>
                {
                    var tcs = new TaskCompletionSource<object>();
                    tcs.SetResult(null);
                    return tcs.Task;
                });
            mailClient2.Setup(m => m.Send(It.IsAny<IEmailBuilder>())).Returns(() =>
                {
                    var tcs = new TaskCompletionSource<object>();
                    tcs.SetResult(null);
                    return tcs.Task;
                });
            
            //Act
            var task = repository.SendMails(emailList);
            task.Wait();

            //Assert
            mailIntialezer.Verify(m => m.Initialize(emailBuilder1.Object, emailList[0]), Times.Once());
            mailIntialezer.Verify(m => m.Initialize(emailBuilder2.Object, emailList[1]), Times.Once());
            mailClient1.Verify(m => m.Send(emailBuilder1.Object), Times.Once());
            mailClient2.Verify(m => m.Send(emailBuilder2.Object), Times.Once());
        }
        public void Setup()
        {
            generator = new ConfigurableIterationGenerator(2);
            mockDice = new Mock<Dice>();
            mockDice.SetupSequence(d => d.Roll(3).d(6).AsSum())
                .Returns(min).Returns(max).Returns(middle)
                .Returns(min - 1).Returns(max + 1).Returns(middle);

            randomizer = new PoorStatsRandomizer(mockDice.Object, generator);
        }
Example #23
0
        public void GetMedia_NormalCase_Saved()
        {
            Mock<ILoggerService> loggerService = new Mock<ILoggerService>();
            loggerService.SetupSequence(o => o.Log(It.IsAny<Log>())).Returns(true);

            FileService Service = new FileService(loggerService.Object);

            byte[] retrieved = Service.GetMedia(this.StoredMedia);
            Assert.AreEqual("System.Byte[]", retrieved.ToString());
        }
Example #24
0
        public void SaveMedia_NormalCase_Saved()
        {
            Mock<ILoggerService> loggerService = new Mock<ILoggerService>();
            loggerService.SetupSequence(o => o.Log(It.IsAny<Log>())).Returns(true);

            FileService Service = new FileService(loggerService.Object);
            string path = "/test.txt";
            bool flag = Service.SaveMedia(path, new byte[1]);
            Assert.IsTrue(flag);
        }
        public void WhenTextReaderReturnsEmptyStringThenCreateEmptyDictionary()
        {
            var mockedTextReader = new Mock<TextReader>();
            mockedTextReader.SetupSequence(p => p.ReadLine())
                .Returns("");

            ISentenceProcessor sentenceProvider = new SentenceProcessor(_standardDelimiters);
            var result = sentenceProvider.Process(mockedTextReader.Object);

            Assert.That(result.Count, Is.EqualTo(0));            
        }
		public void PerformSequenceWithThrowsFirst()
		{
			var mock = new Mock<IFoo>();

			mock.SetupSequence(x => x.Do())
				.Throws<Exception>()
				.Returns(1);

			Assert.Throws<Exception>(() => mock.Object.Do());
			Assert.Equal(1, mock.Object.Do());
		}
        public int TestTakeTurn(int initialPosition, int die1, int die2)
        {
            Mock<IRandomNumberGenerator> randMock = new Mock<IRandomNumberGenerator>();
            randMock.SetupSequence(s => s.Generate(1, MonopolyGame.NUMBER_OF_SIDES)).Returns(die1).Returns(die2);

            Player player = new Player("Car", randMock.Object) { CurrentPosition = initialPosition };

            player.TakeTurn();

            return player.CurrentPosition;
        }
        public void TestGetAllBatches()
        {
            var dateTime1 = DateTime.Now.AddDays(1);
            var dateTime2 = DateTime.Now.AddDays(2);

            var dataReader = new Mock<IDataReader>();
            dataReader.SetupSequence(mocked => mocked.Read()).Returns(true).Returns(true).Returns(false);
            dataReader.SetupSequence(mocked => mocked[0]).Returns(1).Returns(2);
            dataReader.SetupSequence(mocked => mocked[1]).Returns("name1").Returns("name2");
            dataReader.SetupSequence(mocked => mocked[2]).Returns(dateTime1).Returns(dateTime2);
            dataReader.Setup(mocked => mocked.IsDBNull(3)).Returns(false);
            dataReader.SetupSequence(mocked => mocked.GetInt16(3)).Returns(0).Returns(1);

            var dbCommand = new Mock<IDbCommand>();
            dbCommand.Setup(mocked => mocked.Dispose());
            dbCommand.SetupSet(mocked => mocked.CommandType = CommandType.Text).Verifiable();
            dbCommand.SetupSet(mocked => mocked.CommandText = "SELECT ID, IDBatch, DateProcess, Exported FROM Batches  ORDER BY DateProcess DESC").Verifiable();
            dbCommand.Setup(mocked => mocked.ExecuteReader()).Returns(dataReader.Object);

            _dbConnection.Setup(mocked => mocked.Open());
            _dbConnection.Setup(mocked => mocked.CreateCommand()).Returns(dbCommand.Object);
            _dbConnection.Setup(mocked => mocked.Close());

            var result = _fixture.GetBatches(false);
            _dbConnection.VerifyAll();
            dataReader.VerifyAll();
            dbCommand.VerifyAll();

            Assert.IsNotNull(result);
            Assert.AreEqual(2, result.Count);

            Assert.AreEqual(1, result[0].Id);
            Assert.AreEqual("name1", result[0].Name);
            Assert.AreEqual(dateTime1, result[0].ScanDate);
            Assert.AreEqual(BatchStatus.NotExported, result[0].Status);

            Assert.AreEqual(2, result[1].Id);
            Assert.AreEqual("name2", result[1].Name);
            Assert.AreEqual(dateTime2, result[1].ScanDate);
            Assert.AreEqual(BatchStatus.Exported, result[1].Status);
        }
        public void DataReaderPopulatedTableData2x2Reader()
        {
            reader = new Mock<IDataReader>();
            reader.Setup(x => x.FieldCount).Returns(2);
            reader.Setup(x => x.GetName(0)).Returns("a");
            reader.Setup(x => x.GetName(1)).Returns("b");
            reader.SetupSequence(x => x.Read()).Returns(true).Returns(true).Returns(false);
            reader.SetupSequence(x => x.GetValue(0)).Returns(1).Returns(3);
            reader.SetupSequence(x => x.GetValue(1)).Returns(2).Returns(4);

            TableData tableData = new DataReaderPopulatedTableData(reader.Object);

            Assert.AreEqual(2, tableData.ColumnNames.Count);
            Assert.AreEqual("a", tableData.ColumnNames[0]);
            Assert.AreEqual("b", tableData.ColumnNames[1]);
            Assert.AreEqual(2, tableData.Rows.Count);
            Assert.AreEqual(1, tableData.Rows[0][0]);
            Assert.AreEqual(2, tableData.Rows[0][1]);
            Assert.AreEqual(3, tableData.Rows[1][0]);
            Assert.AreEqual(4, tableData.Rows[1][1]);
        }
        public void WhenInputPassedThenCountWithoutCaseSensitivity()
        {
            var mockedTextReader = new Mock<TextReader>();
            mockedTextReader.SetupSequence(p => p.ReadLine())
                .Returns("test")
                .Returns("Test");

            ISentenceProcessor sentenceProvider = new SentenceProcessor(_standardDelimiters);
            var result = sentenceProvider.Process(mockedTextReader.Object);

            Assert.That(result["test"], Is.EqualTo(2));            
        }