Example #1
0
        public void TestMotorSpin()
        {
            var connection = Mock.Create <IConnection>();

            Mock.Arrange(() => connection.WriteValue(Arg.IsAny <byte[]>())).Returns((byte[] b) => true);

            var    motor     = new Motor(connection, Ports.PORT_A);
            ushort time      = 1000;
            sbyte  dutyCycle = -100;

            //message we are expecting to receive
            byte[] data  = { 12, 0, 0x81, (byte)Ports.PORT_A, 0x11, 0x09, 0, 0, 0, 0, 0, 0 };
            byte[] bytes = BitConverter.GetBytes(time);
            Array.Reverse(bytes);
            data[6] = bytes[0];
            data[7] = bytes[1];
            data[8] = (byte)dutyCycle;
            Array.Copy(_trailer, 0, data, 9, _trailer.Length);

            Mock.Arrange(() => connection.WriteValue(data)).Returns((byte[] b) => true).MustBeCalled();
            motor.SetSpeedTimed(time, dutyCycle, 0);

            Mock.Assert(connection);
        }
        public void TestChangeBugStatusToBeCorrect()
        {
            var bug = new Bug
            {
                Id      = 3,
                LogDate = new DateTime(2013, 3, 3),
                Status  = Status.Assigned,
                Text    = "Demo Bug aka. demon"
            };

            Mock.Arrange(() => this.repo.Update(Arg.IsAny <Bug>())).DoInstead <Bug>(b => bug.Status = b.Status);
            Mock.Arrange(() => this.repo.Find(Arg.IsAny <int>())).Returns(bug);

            MyWebApi
            .Controller <BugsController>()
            .WithResolvedDependencyFor <IRepository <Bug> >(this.repo)
            .Calling(c => c.PutBug(bug.Id, new SaveBugModel {
                Status = SaveStatus.Fixed, LogDate = new DateTime(2013, 3, 3), Text = "Bug Changed"
            }))
            .ShouldReturn()
            .Ok();

            Assert.IsTrue(bug.Status == Status.Fixed);
        }
Example #3
0
        private IInternalTransaction BuildTestTransaction(bool isWebTransaction = true, string uri = null, string referrerUri = null, string guid = null, int?statusCode = null, int?subStatusCode = null, string referrerCrossProcessId = null, string transactionCategory = "defaultTxCategory", string transactionName = "defaultTxName", ErrorData exceptionData = null, ErrorData customErrorData = null, bool isSynthetics = true, bool isCAT = true, bool includeUserAttributes = false, float priority = 0.5f, bool sampled = false, string traceId = "traceId")
        {
            var name = isWebTransaction
                ? TransactionName.ForWebTransaction(transactionCategory, transactionName)
                : TransactionName.ForOtherTransaction(transactionCategory, transactionName);

            var segments = Enumerable.Empty <Segment>();

            var placeholderMetadataBuilder = new TransactionMetadata();
            var placeholderMetadata        = placeholderMetadataBuilder.ConvertToImmutableMetadata();

            var immutableTransaction = new ImmutableTransaction(name, segments, placeholderMetadata, DateTime.UtcNow, TimeSpan.FromSeconds(10), TimeSpan.FromSeconds(10), guid, false, false, false, priority, sampled, traceId, null, _attribDefs);

            var internalTransaction = new Transaction(Mock.Create <IConfiguration>(), immutableTransaction.TransactionName, _timerFactory.StartNewTimer(), DateTime.UtcNow, Mock.Create <ICallStackManager>(), Mock.Create <IDatabaseService>(), priority, Mock.Create <IDatabaseStatementParser>(), Mock.Create <IDistributedTracePayloadHandler>(), Mock.Create <IErrorService>(), _attribDefs);

            var adaptiveSampler = Mock.Create <IAdaptiveSampler>();

            Mock.Arrange(() => adaptiveSampler.ComputeSampled(ref priority)).Returns(sampled);
            internalTransaction.SetSampled(adaptiveSampler);

            PopulateTransactionMetadataBuilder(internalTransaction, uri, statusCode, subStatusCode, referrerCrossProcessId, exceptionData, customErrorData, isSynthetics, isCAT, referrerUri, includeUserAttributes);

            return(internalTransaction);
        }
Example #4
0
        public void MetricsAreCorrectAfterHarvestRetryIfSendResponseEqualsDiscard()
        {
            const int eventCount = 2;
            // Arrange
            var firstTime      = true;
            var sentEventCount = int.MinValue;

            Mock.Arrange(() => _dataTransportService.Send(Arg.IsAny <EventHarvestData>(), Arg.IsAny <IEnumerable <ISpanEventWireModel> >()))
            .Returns <EventHarvestData, IEnumerable <ISpanEventWireModel> >((_, events) =>
            {
                sentEventCount  = events.Count();
                var returnValue = firstTime ? DataTransportResponseStatus.Retain : DataTransportResponseStatus.RequestSuccessful;
                firstTime       = false;
                return(returnValue);
            });

            CollectSpanEvents(eventCount);

            //this harvest's Send() will fail with the value in response variable
            _harvestAction();

            //EventsSent should not happen due to error
            Mock.Assert(() => _agentHealthReporter.ReportSpanEventsSent(Arg.IsAny <int>()), Occurs.Never());

            sentEventCount = int.MinValue; // reset

            // Act
            //this harvest's Send() will succeeed
            _harvestAction();

            Mock.Assert(() => _agentHealthReporter.ReportSpanEventCollected(eventCount));
            Mock.Assert(() => _agentHealthReporter.ReportSpanEventsSent(eventCount));

            // Assert
            Assert.That(sentEventCount, Is.EqualTo(eventCount));
        }
Example #5
0
        public void ZeroEventsAreRetainedAfterHarvestIfResponseEqualsPostTooBigErrorWithOnlyOneEventInPost()
        {
            const int eventCount = 1;
            // Arrange
            IEnumerable <SpanAttributeValueCollection> sentEvents = null;

            Mock.Arrange(() => _dataTransportService.Send(Arg.IsAny <EventHarvestData>(), Arg.IsAny <IEnumerable <SpanAttributeValueCollection> >()))
            .Returns <EventHarvestData, IEnumerable <SpanAttributeValueCollection> >((_, events) =>
            {
                sentEvents = events;
                return(DataTransportResponseStatus.ReduceSizeIfPossibleOtherwiseDiscard);
            });

            CollectSpanEvents(eventCount);

            _harvestAction();
            sentEvents = null; // reset

            // Act
            _harvestAction();

            // Assert
            Assert.That(sentEvents, Is.Null);
        }
Example #6
0
        public void EventsAreRetainedAfterHarvestIfResponseEqualsRetain()
        {
            const int eventCount = 2;
            // Arrange
            var sentEventCount = int.MinValue;

            Mock.Arrange(() => _dataTransportService.Send(Arg.IsAny <EventHarvestData>(), Arg.IsAny <IEnumerable <ISpanEventWireModel> >()))
            .Returns <EventHarvestData, IEnumerable <ISpanEventWireModel> >((_, events) =>
            {
                sentEventCount = events.Count();
                return(DataTransportResponseStatus.Retain);
            });

            CollectSpanEvents(eventCount);

            _harvestAction();
            sentEventCount = int.MinValue; // reset

            // Act
            _harvestAction();

            // Assert
            Assert.That(sentEventCount, Is.EqualTo(eventCount));
        }
Example #7
0
        public void SetUp()
        {
            var configuration = GetDefaultConfiguration();

            Mock.Arrange(() => configuration.CollectorSendDataOnExit).Returns(true);
            Mock.Arrange(() => configuration.CollectorSendDataOnExitThreshold).Returns(0);
            Mock.Arrange(() => configuration.SpanEventsHarvestCycle).Returns(ConfiguredHarvestCycle);
            _configurationAutoResponder = new ConfigurationAutoResponder(configuration);

            _dataTransportService = Mock.Create <IDataTransportService>();
            _spanStreamingService = Mock.Create <IDataStreamingService <Span, SpanBatch, RecordStatus> >();
            _agentHealthReporter  = Mock.Create <IAgentHealthReporter>();
            _processStatic        = Mock.Create <IProcessStatic>();

            _scheduler = Mock.Create <IScheduler>();

            Mock.Arrange(() => _scheduler.ExecuteEvery(Arg.IsAny <Action>(), Arg.IsAny <TimeSpan>(), Arg.IsAny <TimeSpan?>()))
            .DoInstead <Action, TimeSpan, TimeSpan?>((action, harvestCycle, __) =>
            {
                _harvestAction     = action;
                _harvestCycle      = harvestCycle;
                _actualWillHarvest = true;
            });

            Mock.Arrange(() => _scheduler.StopExecuting(Arg.IsAny <Action>(), Arg.IsAny <TimeSpan?>()))
            .DoInstead <Action, TimeSpan?>((action, __) =>
            {
                _actualWillHarvest = false;
            });

            _actualWillHarvest = false;

            _spanEventAggregator = new SpanEventAggregator(_dataTransportService, _scheduler, _processStatic, _agentHealthReporter);

            EventBus <AgentConnectedEvent> .Publish(new AgentConnectedEvent());
        }
        public void Harvest_SendsApmRequiredMetricEvenIfNoOtherMetricsExist()
        {
            var sentMetrics = Enumerable.Empty <MetricWireModel>();

            Mock.Arrange(() => _dataTransportService.Send(Arg.IsAny <IEnumerable <MetricWireModel> >()))
            .DoInstead <IEnumerable <MetricWireModel> >(metrics => sentMetrics = metrics);

            _harvestAction();

            Assert.NotNull(sentMetrics);
            Assert.AreEqual(1, sentMetrics.Count());
            var sentMetric = sentMetrics.ElementAt(0);

            NrAssert.Multiple(
                () => Assert.AreEqual(MetricNames.SupportabilityMetricHarvestTransmit, sentMetric.MetricName.Name),
                () => Assert.AreEqual(null, sentMetric.MetricName.Scope),
                () => Assert.AreEqual(1, sentMetric.Data.Value0),
                () => Assert.AreEqual(0, sentMetric.Data.Value1),
                () => Assert.AreEqual(0, sentMetric.Data.Value2),
                () => Assert.AreEqual(0, sentMetric.Data.Value3),
                () => Assert.AreEqual(0, sentMetric.Data.Value4),
                () => Assert.AreEqual(0, sentMetric.Data.Value5)
                );
        }
        public void SetUp()
        {
            var configuration = Mock.Create <IConfiguration>();

            Mock.Arrange(() => configuration.CollectorSendDataOnExit).Returns(true);
            Mock.Arrange(() => configuration.CollectorSendDataOnExitThreshold).Returns(0);
            Mock.Arrange(() => configuration.TransactionTracerEnabled).Returns(true);
            _configurationAutoResponder = new ConfigurationAutoResponder(configuration);

            _dataTransportService = Mock.Create <IDataTransportService>();
            _dnsStatic            = Mock.Create <IDnsStatic>();
            _processStatic        = Mock.Create <IProcessStatic>();

            _transactionCollector1 = Mock.Create <ITransactionCollector>();
            _transactionCollector2 = Mock.Create <ITransactionCollector>();
            _transactionCollectors = new[] { _transactionCollector1, _transactionCollector2 };

            _scheduler = Mock.Create <IScheduler>();
            Mock.Arrange(() => _scheduler.ExecuteEvery(Arg.IsAny <Action>(), Arg.IsAny <TimeSpan>(), Arg.IsAny <TimeSpan?>()))
            .DoInstead <Action, TimeSpan, TimeSpan?>((action, harvestCycle, __) => { _harvestAction = action; _harvestCycle = harvestCycle; });
            _transactionTraceAggregator = new TransactionTraceAggregator(_dataTransportService, _scheduler, _processStatic, _transactionCollectors);

            EventBus <AgentConnectedEvent> .Publish(new AgentConnectedEvent());
        }
        public void When_A_New_Message_After_Consuming_An_Incoming_Message_Is_Produced_Which_Has_A_CorrelationId_Set_We_Should_Not_Reuse_That_CorrelationId()
        {
            var correlationId          = Guid.NewGuid();
            var inMessageCorrelationId = Guid.NewGuid();

            var correlationPersister = Mock.Create <IPersistCorrelation>();

            // OnProduce should fire and set the correct correlation id
            var intercepter = Mock.Create <HandlerAuditIntercepter>(
                Mock.Create <ILogger>(),
                Mock.Create <IConnectionFactory>(),
                Mock.Create <ISerializer>(),
                Mock.Create <ITypeNameSerializer>(),
                correlationPersister);

            Mock.Arrange(() => correlationPersister.CorrelationId).Returns(correlationId);

            Mock.Arrange(() => intercepter.OnProduce(Arg.IsAny <RawMessage>())).CallOriginal();
            Mock.Arrange(() => intercepter.ShouldAudit()).Returns(true);
            Mock.Arrange(() => intercepter.GenerateNewCorrelationId()).CallOriginal().OccursNever("There should not be a request for a new correlation id if one is present.");

            var rawMessage = new RawMessage(
                new MessageProperties()
            {
                TypePresent          = true,
                Type                 = "MyAssembly",
                CorrelationIdPresent = true,
                CorrelationId        = inMessageCorrelationId.ToString(),
            }, Encoding.UTF8.GetBytes("my message"));

            var t = intercepter.OnProduce(rawMessage);

            Assert.IsTrue(t.Properties.CorrelationIdPresent, "Missing correlation id present property.");
            Assert.AreNotEqual(inMessageCorrelationId.ToString(), t.Properties.CorrelationId, "The correlationid should not be reused.");
            Mock.Assert(intercepter);
        }
        public void Add_ShouldLogSuccessfulMessage_WhenPassedValidTask()
        {
            // Arrange
            //var loggerMock = new Mock<ILogger>();
            //var idProviderStub = new Mock<IIdProvider>();
            //var taskStub = new Mock<ITask>();

            var loggerMock     = Mock.Create <ILogger>();
            var idProviderStub = Mock.Create <IIdProvider>();
            var taskStub       = Mock.Create <ITask>();

            var manager = new TaskManager(idProviderStub, loggerMock);
            var list    = new List();

            Mock.Arrange(() => idProviderStub.NextId()).Returns(0);
            idProviderStub.Setup(x => x.NextId()).Return(0);

            // Act
            manager.Add(taskStub);

            // Assert
            //loggerMock.Verify(x => x.Log(It.IsAny<string>()), Times.Exactly(1));
            Mock.Assert(() => loggerMock.Log(Arg.AnyString), Occurs.Once());
        }
Example #12
0
        public void Events_send_on_harvest()
        {
            // Arrange
            var sentEvents = null as IEnumerable <ErrorEventWireModel>;

            Mock.Arrange(() => _dataTransportService.Send(Arg.IsAny <EventHarvestData>(), Arg.IsAny <IEnumerable <ErrorEventWireModel> >()))
            .DoInstead <EventHarvestData, IEnumerable <ErrorEventWireModel> >((_, events) => sentEvents = events);

            var eventsToSend = new[]
            {
                new ErrorEventWireModel(_attribValues, false, 0.3f),
                new ErrorEventWireModel(_attribValues, false, 0.2f),
                new ErrorEventWireModel(_attribValues, false, 0.1f)
            };

            eventsToSend.ForEach(_errorEventAggregator.Collect);

            // Act
            _harvestAction();

            // Assert
            Assert.AreEqual(3, sentEvents.Count());
            Assert.AreEqual(sentEvents, eventsToSend);
        }
Example #13
0
        public void GraphicsPathTest()
        {
            var figure = Mock.Create <Figure>(() => new Figure(new Pen(Color.AliceBlue), new GraphicsPath(), Color.Bisque, 1, false));

            Mock.Arrange(() => figure.Path).Returns(new GraphicsPath());
        }
Example #14
0
        public void synthetics_header_can_be_decoded_from_outbound_request()
        {
            // ARRANGE
            var encodingKey     = "foo";
            var version         = 1;
            var clientAccountId = 123;
            var resourceId      = "resourceId";
            var jobId           = "jobId";
            var monitorId       = "monitorId";

            _compositeTestAgent.ServerConfiguration.TrustedIds  = new long[] { clientAccountId };
            _compositeTestAgent.ServerConfiguration.CatId       = "123#456";
            _compositeTestAgent.ServerConfiguration.EncodingKey = encodingKey;
            _compositeTestAgent.PushConfiguration();

            var syntheticsHeaderValue = Strings.Base64Encode(
                string.Format(@"[{0}, {1}, ""{2}"", ""{3}"", ""{4}""]", version, clientAccountId, resourceId, jobId,
                              monitorId), encodingKey);
            var requestHeaders = new List <KeyValuePair <string, string> >()
            {
                new KeyValuePair <string, string>(SyntheticsHeaderKey, syntheticsHeaderValue)
            };

            // ==== ACT ====
            var tx = _agent.CreateTransaction(
                isWeb: true,
                category: EnumNameCache <WebTransactionType> .GetName(WebTransactionType.Action),
                transactionDisplayName: "name",
                doNotTrackAsUnitOfWork: true);

            tx.AcceptDistributedTraceHeaders(requestHeaders, HeaderFunctions.GetHeaders, TransportType.HTTP);

            var headers = _agent.CurrentTransaction.GetRequestMetadata().ToDictionary();

            Assert.NotNull(headers);

            var configurationService = Mock.Create <IConfigurationService>();

            Mock.Arrange(() => configurationService.Configuration).Returns(() => _compositeTestAgent.CurrentConfiguration);

            var syntheticsHeaderHandler = new SyntheticsHeaderHandler(configurationService);
            SyntheticsHeader decodedSyntheticsHeader = syntheticsHeaderHandler.TryDecodeInboundRequestHeaders(headers, GetHeaderValue);

            NrAssert.Multiple(
                () => Assert.AreEqual("PV5DV11cSk0dAxwAEx0MAyYLRENNDAANLwtNSk0CCQEGEgAdLwtNOw==", headers[SyntheticsHeaderKey]),
                () => Assert.AreEqual(decodedSyntheticsHeader.Version, version),
                () => Assert.AreEqual(decodedSyntheticsHeader.JobId, jobId),
                () => Assert.AreEqual(decodedSyntheticsHeader.AccountId, clientAccountId),
                () => Assert.AreEqual(decodedSyntheticsHeader.MonitorId, monitorId),
                () => Assert.AreEqual(decodedSyntheticsHeader.ResourceId, resourceId)
                );

            List <string> GetHeaderValue(Dictionary <string, string> carrier, string key)
            {
                var headerValues = new List <string>();

                foreach (var item in carrier)
                {
                    if (item.Key.Equals(key, StringComparison.OrdinalIgnoreCase))
                    {
                        headerValues.Add(item.Value);
                    }
                }
                return(headerValues);
            }
        }
        public void Init()
        {
            #region Dummy Lists
            var passwordSalt1 = PasswordUtilities.CreateSalt(16);
            var password1     = PasswordUtilities.GenerateSHA256Hash("12345", passwordSalt1);

            clients = new List <Client>
            {
                new Client {
                    ClientID = 1, FirstName = "John", LastName = "Doe", DocType = "DNI", DocNumber = 34578800, BirthDate = new DateTime(1990, 12, 31),
                    DateFrom = new DateTime(2008, 09, 01), Email = "*****@*****.**",
                    Password = password1, PasswordSalt = passwordSalt1, Role = Catalog.Roles.Client, Sexo = Catalog.Genre.Hombre
                },

                new Client {
                    ClientID = 2, FirstName = "Cristian", LastName = "Piqué", DocType = "DNI", DocNumber = 34578644, BirthDate = new DateTime(1989, 12, 31),
                    DateFrom = new DateTime(2008, 09, 01), Email = "*****@*****.**",
                    Password = password1, PasswordSalt = passwordSalt1, Role = Catalog.Roles.Admin, Sexo = Catalog.Genre.Hombre
                },

                new Client {
                    ClientID = 3, FirstName = "José", LastName = "Pérez", DocType = "DNI", DocNumber = 34578644, BirthDate = new DateTime(1982, 12, 31),
                    DateFrom = new DateTime(2014, 09, 01), Email = "*****@*****.**",
                    Password = password1, PasswordSalt = passwordSalt1, Role = Catalog.Roles.Instructor, Sexo = Catalog.Genre.Hombre
                },

                new Client {
                    ClientID = 4, FirstName = "Ray", LastName = "Allen", DocType = "DNI", DocNumber = 34578644, BirthDate = new DateTime(1992, 12, 31),
                    DateFrom = new DateTime(2014, 09, 01), Email = "*****@*****.**",
                    Password = password1, PasswordSalt = passwordSalt1, Role = Catalog.Roles.Client, Sexo = Catalog.Genre.Hombre
                },

                new Client {
                    ClientID = 5, FirstName = "Enzo", LastName = "Gutiérrez", DocType = "DNI", DocNumber = 34578644, BirthDate = new DateTime(1991, 12, 31),
                    DateFrom = new DateTime(2014, 09, 01), Email = "*****@*****.**",
                    Password = password1, PasswordSalt = passwordSalt1, Role = Catalog.Roles.Client, Sexo = Catalog.Genre.Hombre
                },

                new Client {
                    ClientID = 6, FirstName = "Juana", LastName = "Pérez", DocType = "DNI", DocNumber = 33123654, BirthDate = new DateTime(1979, 08, 11),
                    DateFrom = new DateTime(2015, 09, 01), Email = "*****@*****.**",
                    Password = password1, PasswordSalt = passwordSalt1, Role = Catalog.Roles.Client, Sexo = Catalog.Genre.Mujer
                },

                new Client {
                    ClientID = 7, FirstName = "Carolina", LastName = "García", DocType = "DNI", DocNumber = 12345678, BirthDate = new DateTime(1971, 11, 15),
                    DateFrom = new DateTime(2015, 09, 01), Email = "*****@*****.**",
                    Password = password1, PasswordSalt = passwordSalt1, Role = Catalog.Roles.Instructor, Sexo = Catalog.Genre.Mujer
                },

                new Client {
                    ClientID = 8, FirstName = "Martina", LastName = "Núñez", DocType = "DNI", DocNumber = 34578644, BirthDate = new DateTime(1981, 02, 01),
                    DateFrom = new DateTime(2015, 09, 01), Email = "*****@*****.**",
                    Password = password1, PasswordSalt = passwordSalt1, Role = Catalog.Roles.Client, Sexo = Catalog.Genre.Mujer
                },

                new Client {
                    ClientID = 9, FirstName = "Sol", LastName = "Rodríguez", DocType = "DNI", DocNumber = 34578644, BirthDate = new DateTime(1991, 12, 31),
                    DateFrom = new DateTime(2015, 09, 01), Email = "*****@*****.**",
                    Password = password1, PasswordSalt = passwordSalt1, Role = Catalog.Roles.Client, Sexo = Catalog.Genre.Mujer
                },

                new Client {
                    ClientID = 10, FirstName = "José", LastName = "García", DocType = "DNI", DocNumber = 34578644, BirthDate = new DateTime(1986, 12, 31),
                    DateFrom = new DateTime(2016, 09, 01), Email = "*****@*****.**",
                    Password = password1, PasswordSalt = passwordSalt1, Role = Catalog.Roles.Client, Sexo = Catalog.Genre.Hombre
                }
            };

            medicalRecords = new List <MedicalRecord>
            {
                new MedicalRecord {
                    ClientID = 1, Age = 26, Gender = 'M', Heigth = 1.81, Weight = 77
                },
                new MedicalRecord {
                    ClientID = 2, Age = 33, Gender = 'F', Heigth = 1.81, Weight = 75
                },
                new MedicalRecord {
                    ClientID = 3, Age = 28, Gender = 'F', Heigth = 1.81, Weight = 75
                },
                new MedicalRecord {
                    ClientID = 4, Age = 23, Gender = 'M', Heigth = 1.81, Weight = 79
                },
                new MedicalRecord {
                    ClientID = 5, Age = 26, Gender = 'M', Heigth = 1.81, Weight = 75
                },
                new MedicalRecord {
                    ClientID = 6, Age = 26, Gender = 'F', Heigth = 1.81, Weight = 75
                },
                new MedicalRecord {
                    ClientID = 7, Age = 25, Gender = 'M', Heigth = 1.81, Weight = 88
                },
                new MedicalRecord {
                    ClientID = 8, Age = 26, Gender = 'M', Heigth = 1.81, Weight = 75
                },
                new MedicalRecord {
                    ClientID = 10, Age = 18, Gender = 'M', Heigth = 1.81, Weight = 75
                },
                new MedicalRecord {
                    ClientID = 4, Age = 26, Gender = 'M', Heigth = 1.81, Weight = 75
                },
            };
            #endregion

            #region Repositories
            clientRepository        = Mock.Create <IClientRepository>();
            medicalRecordRepository = Mock.Create <IMedicalRecordRepository>();
            context  = Mock.Create <HttpContextBase>();
            request  = Mock.Create <HttpRequestBase>();
            response = Mock.Create <HttpResponseBase>();
            session  = Mock.Create <HttpSessionStateBase>();
            server   = Mock.Create <HttpServerUtilityBase>();
            #endregion

            #region Controller
            controller = new DashBoardController(clientRepository, medicalRecordRepository);
            #endregion

            #region Fake Context
            Mock.Arrange(() => clientRepository
                         .GetClientByID(CLIENT_ID_TO_USE))
            .Returns(clients.Where(c => c.ClientID == CLIENT_ID_TO_USE)
                     .FirstOrDefault());

            Mock.Arrange(() => context.Request).Returns(request);
            Mock.Arrange(() => context.Response).Returns(response);
            Mock.Arrange(() => context.Session).Returns(session);
            Mock.Arrange(() => context.Server).Returns(server);
            Mock.Arrange(() => session["UserData"]).Returns(clients.Where(c => c.ClientID == CLIENT_ID_TO_USE));
            #endregion

            #region JustMock
            #endregion
        }
Example #16
0
        public void BuildVolaryTest()
        {
            // Кімната з чотирма вольєрами
            Room Room1 = new Room();

            Room1.volary = new Volary();
            for (int i = 0; i < 3; i++)
            {
                Room1.volary.buildVolary();
            }
            string Room1expected = "Неможливо збудувати вольєр! Немає вiльної кімнати!";

            string Room1actual = Room1.BuildVolary();

            Assert.AreEqual(Room1expected, Room1actual);

            //Кімната з чотирма вольєрами і іншою кімнатою

            bool     room2expected = false;
            Room     room2         = new Room();
            RoomStub roomStub2     = new RoomStub();

            room2.room = roomStub2;
            Mock.Arrange(() => roomStub2.BuildVolary()).DoInstead(() => room2expected = true);
            room2.volary = new Volary();
            for (int i = 0; i < 3; i++)
            {
                room2.volary.buildVolary();
            }

            room2.BuildVolary();

            Assert.IsTrue(room2expected);

            // Зайнята кімната
            string Room3expected = "Неможливо збудувати вольєр! Немає вiльної кімнати!";
            Room   room3         = new Room();
            Cat    cat           = new Cat("Мурзик", "ч");

            room3.animals.Add(cat);

            string room3actual = room3.BuildVolary();

            Assert.AreEqual(Room3expected, room3actual);

            // Зайнята кімната з іншою кімнатою

            bool     room4expected = false;
            Room     room4         = new Room();
            RoomStub roomStub4     = new RoomStub();

            room4.room = roomStub4;
            Mock.Arrange(() => roomStub4.BuildVolary()).DoInstead(() => room4expected = true);
            room4.volary = new Volary();
            for (int i = 0; i < 3; i++)
            {
                room4.volary.buildVolary();
            }
            Cat cat2 = new Cat("Пиріжок", "ч");

            room4.animals.Add(cat2);

            room4.BuildVolary();

            Assert.IsTrue(room4expected);

            // Кімната з менш ніж чотирма вольєрами

            Room room5 = new Room();

            room5.volary = new Volary();
            string room5expected = "Новий вольер збудовано.";
            string room5actual   = "";

            Mock.Arrange(() => room5.volary.buildVolary()).DoInstead(() => room5actual = room5expected);

            room5.BuildVolary();

            Assert.AreEqual(room5expected, room5actual);

            // Пуста кімната

            Room   room6         = new Room();
            string room6expected = "Новий вольер збудовано.";

            string room6actual = room6.BuildVolary();

            Assert.AreEqual(room6expected, room6actual);
        }
Example #17
0
 public void ShouldUpdateContextInFluentAssert()
 {
     Mock.Arrange(() => mock.Dispose());
 }
Example #18
0
        public void ShouldFailToChainReturnsCallToVoidMethod()
        {
            var mock = Mock.Create <IAction>();

            Assert.Throws <MockException>(() => Mock.Arrange(() => mock.Do()).Returns(123));
        }
Example #19
0
 private void SetLastInputTick(long tick)
 {
     Mock.Arrange(() => probeMock.GetLastInputTick()).Returns(tick);
 }
Example #20
0
 public void SetUp()
 {
     _transactionSegmentState = Mock.Create <ITransactionSegmentState>();
     Mock.Arrange(() => _transactionSegmentState.AttribDefs).Returns(() => new AttributeDefinitions(new AttributeFilter(new AttributeFilter.Settings())));
 }
        public void AccountDetails_Check_That_AccountSum_Is_Same_As_TransferSum()
        {
            // Arange
            var transfersRepository = Mock.Create <IRepository>();

            Mock.Arrange(() => transfersRepository.GetAllAccounts()).
            Returns(new List <Account>()
            {
                new Account {
                    Id = 1, Number = "123456-1", Name = "Betalkonto", Sum = 350.0, Type = "-", Locked = false
                },
                new Account {
                    Id = 2, Number = "123456-2", Name = "Lönekonto", Sum = 450.0, Type = "-", Locked = false
                },
                new Account {
                    Id = 3, Number = "123456-3", Name = "Sparkonto 1", Sum = 575.0, Type = "-", Locked = false
                },
                new Account {
                    Id = 4, Number = "123456-4", Name = "Sparkonto 2", Sum = 625.0, Type = "-", Locked = false
                }
            }).MustBeCalled();

            Mock.Arrange(() => transfersRepository.GetAllTransfers()).
            Returns(new List <Transfer>()
            {
                new Transfer {
                    Id = 1, IdFrom = 0, IdTo = 1, Sum = 500.0, Time = DateTime.Now
                },
                new Transfer {
                    Id = 2, IdFrom = 0, IdTo = 2, Sum = 500.0, Time = DateTime.Now
                },
                new Transfer {
                    Id = 3, IdFrom = 0, IdTo = 3, Sum = 500.0, Time = DateTime.Now
                },
                new Transfer {
                    Id = 4, IdFrom = 0, IdTo = 4, Sum = 500.0, Time = DateTime.Now
                },
                new Transfer {
                    Id = 5, IdFrom = 2, IdTo = 1, Sum = 150.0, Time = DateTime.Now
                },
                new Transfer {
                    Id = 6, IdFrom = 3, IdTo = 2, Sum = 100.0, Time = DateTime.Now
                },
                new Transfer {
                    Id = 7, IdFrom = 1, IdTo = 3, Sum = 175.0, Time = DateTime.Now
                },
                new Transfer {
                    Id = 8, IdFrom = 1, IdTo = 4, Sum = 125.0, Time = DateTime.Now
                }
            }).MustBeCalled();

            // Act
            AccountsController controller = new AccountsController(transfersRepository);
            ViewResult         viewResult = (ViewResult)controller.AccountDetails(2);
            var model    = viewResult.Model as IEnumerable <Transfer>;
            var plusSum  = model.ToList().Where(x => x.IdTo == 2).Sum(p => p.Sum);
            var minusSum = model.ToList().Where(x => x.IdFrom == 2).Sum(p => p.Sum);

            // Assert
            Assert.IsNotNull(viewResult.ViewBag.Account);
            Assert.IsNotNull(model);
            Assert.AreEqual(viewResult.ViewBag.Account.Sum, plusSum - minusSum);
        }
Example #22
0
        public void CurrentFigureTest(int n)
        {
            var figure = Mock.Create <Figure>(() => new Figure(new Pen(Color.AliceBlue), new GraphicsPath(), Color.Bisque, 1, false));

            Mock.Arrange(() => figure.CurrentFigure).Returns(n);
        }
Example #23
0
        public void SelectFigureTest(bool b)
        {
            var figure = Mock.Create <Figure>(() => new Figure(new Pen(Color.AliceBlue), new GraphicsPath(), Color.Bisque, 1, false));

            Mock.Arrange(() => figure.SelectFigure).Returns(b);
        }
Example #24
0
 public void ShouldSetUseContextualRepositoryForRecursiveMock()
 {
     Mock.Arrange(() => mock.Item.Id).Returns(5);
     Assert.Equal(5, mock.Item.Id);
 }
Example #25
0
 public void ShouldCreateInOrderArrangementOnNonMock()
 {
     Mock.Arrange(() => Arg.IsAny <List <string> >().Add("a")).InOrder();
 }
 public void SetUp()
 {
     _metricNameService = Mock.Create <IMetricNameService>();
     Mock.Arrange(() => _metricNameService.RenameMetric(Arg.IsAny <string>())).Returns <string>(name => name);
     _metricBuilder = new MetricWireModel.MetricBuilder(_metricNameService);
 }
Example #27
0
 private void SetCurrentTime(DateTime time)
 {
     Mock.Arrange(() => clockMock.CurrentTime()).Returns(time);
 }
Example #28
0
        public void ShouldArrangeMultipleInstancesSeparatelyByPropertyName()
        {
            var container = new MockingContainer <TransactionService>();

            container.Bind <IAccount>().ToMock().InjectedIntoProperty("BillingAccount").AndArrange(x => Mock.Arrange(() => x.Id).Returns(30));

            var inst = container.Instance;

            Assert.Equal(30, inst.BillingAccount.Id);
        }
        public void WhenUserPlacesACorrectOrderWithMoreThenOneItemThenAnOrderNumberShouldBeReturned()
        {
            //Arrange
            var shoppingCart    = new ShoppingCart();
            var itemOneId       = Guid.NewGuid();
            var itemTwoId       = Guid.NewGuid();
            int itemOneQuantity = 1;
            int itemTwoQuantity = 4;

            shoppingCart.Items
            .Add(new ShoppingCartItem {
                ItemId = itemOneId, Quantity = itemOneQuantity
            });
            shoppingCart
            .Items.Add(new ShoppingCartItem {
                ItemId = itemTwoId, Quantity = itemTwoQuantity
            });

            var customerId = Guid.NewGuid();
            var customer   = new Customer {
                Id = customerId
            };

            var expectedOrderId           = Guid.NewGuid();
            var orderFulfillmentSessionId = Guid.NewGuid();

            Mock.Arrange(() => orderDataService.Save(Arg.IsAny <Order>()))
            .Returns(expectedOrderId)
            .OccursOnce();

            Mock.Arrange(() => customerService.GetCustomer(customerId))
            .Returns(customer)
            .OccursOnce();

            Mock.Arrange(() => orderFulfillmentService
                         .OpenSession(Arg.IsAny <string>(), Arg.IsAny <string>()))
            .Returns(orderFulfillmentSessionId);


            Mock.Arrange(() => orderFulfillmentService
                         .IsInInventory(orderFulfillmentSessionId, itemOneId, itemOneQuantity))
            .Returns(true)
            .OccursOnce();


            Mock.Arrange(() => orderFulfillmentService
                         .IsInInventory(orderFulfillmentSessionId, itemTwoId, itemTwoQuantity))
            .Returns(true)
            .OccursOnce();


            Mock.Arrange(() => orderFulfillmentService
                         .PlaceOrder(orderFulfillmentSessionId, Arg.IsAny <IDictionary <Guid, int> >(), Arg.IsAny <string>()))
            .Returns(true);

            // Act
            var result = orderService.PlaceOrder(customerId, shoppingCart);

            //Assert
            Assert.That(expectedOrderId, Is.EqualTo(result));
            Mock.Assert(orderDataService);
            Mock.Assert(orderFulfillmentService);
        }
Example #30
0
        public void ShouldMockMethodWithReturnTypeSameAsDeclaringClass()
        {
            var selectionData = Mock.Create <ILinkedListNode>();

            Mock.Arrange(() => selectionData.Tail).Returns(null as ILinkedListNode);
        }