Exemplo n.º 1
0
        public void VerifyGet <TProperty>(
            Expression <Func <TAnalog, TProperty> > expression,
            Times?times        = null,
            string failMessage = null
            )
        {
            Guard.NotNull(expression, nameof(expression));

            Expression <Func <T, TProperty> > rewrittenExpression;

            try
            {
                rewrittenExpression = (Expression <Func <T, TProperty> >)ReplaceDuck(expression);
            }
            catch (ArgumentException ex)
            {
                throw new ArgumentException(ex.Message, nameof(expression));
            }

            Mock.VerifyGet(
                this.mock,
                rewrittenExpression,
                times ?? Times.AtLeastOnce(),
                failMessage
                );
        }
Exemplo n.º 2
0
        public void VerifySet_Should_Work()
        {
            void VerifySet(Times?times = null, string failMessage = null)
            {
                this.protectedMock.VerifySet(
                    o => o[
                        It.IsInRange(0, 5, Moq.Range.Inclusive),
                        It.IsIn("Bad", "JustAsBad")
                    ] = It.Is <int>(i => i > 10),
                    times,
                    failMessage
                    );
            }

            VerifySet(Times.Never());

            mock.Object.SetMultipleIndexer(1, "Ok", 1);
            VerifySet(Times.Never());

            Assert.Throws <MockException>(() => VerifySet());            // AtLeastOnce

            mock.Object.SetMultipleIndexer(1, "Bad", 999);
            VerifySet();             // AtLeastOnce

            mock.Object.SetMultipleIndexer(1, "JustAsBad", 12);
            VerifySet(Times.Exactly(2));

            Assert.Throws <MockException>(() => VerifySet(Times.AtMostOnce()));

            var mockException = Assert.Throws <MockException>(() => VerifySet(Times.AtMostOnce(), "custom fail message"));

            Assert.StartsWith("custom fail message", mockException.Message);
        }
Exemplo n.º 3
0
        private static void VerifyLog(this Mock <ILogger> mockLogger, string messagePattern,
                                      Expression <Func <Exception, bool> > hasMatchingException, object extendedProperties,
                                      LogLevel?logLevel, Times?times, string failMessage)
        {
            if (mockLogger == null)
            {
                throw new ArgumentNullException(nameof(mockLogger));
            }

            Expression <Func <LogEntry, bool> > matchingMessage = null, matchingExtendedProperties = null, matchingLogLevel = null;

            if (messagePattern != null)
            {
                matchingMessage = GetMatchingMessageExpression(messagePattern);
            }

            if (extendedProperties != null)
            {
                matchingExtendedProperties = GetMatchingExtendedPropertiesExpression(extendedProperties);
            }

            if (logLevel != null)
            {
                matchingLogLevel = GetMatchingLogLevelExpression(logLevel.Value);
            }

            var matchingLogEntry = GetMatchingLogEntryExpression(matchingMessage, matchingLogLevel, hasMatchingException, matchingExtendedProperties);

            mockLogger.Verify(mock => mock.Log(It.Is(matchingLogEntry), It.IsAny <string>(), It.IsAny <string>(), It.IsAny <int>()),
                              times ?? Times.Once(), failMessage);
        }
Exemplo n.º 4
0
 public static void VerifyExecuteQuery <TQuery, TResult>(
     this Mock <CosmosDbQueryDispatcher> mock,
     Expression <Func <TQuery, bool> > match,
     Times?times = null)
     where TQuery : ICosmosDbQuery <TResult>
 {
     mock.Verify(mock => mock.ExecuteQuery(It.Is(match)), times ?? Times.Once());
 }
Exemplo n.º 5
0
        public void VerifySet(Action <TAnalog> setterExpression, Times?times = null, string failMessage = null)
        {
            Guard.NotNull(setterExpression, nameof(setterExpression));

            var rewrittenExpression = ReconstructAndReplaceSetter(setterExpression);

            Mock.VerifySet(mock, rewrittenExpression, times.HasValue ? times.Value : Times.AtLeastOnce(), failMessage);
        }
 private void VerifyAnalyticsTrackEvent(Times?times = null)
 {
     mockAnalytics.Verify(
         c => c.TrackEvent(
             "HTTP Error",
             It.IsAny <Dictionary <string, string> >()),
         times ?? Times.Once());
 }
 /// <summary>
 ///     Verify mock service short method.
 /// </summary>
 /// <param name="sut"></param>
 /// <param name="expression">Expression for verify</param>
 /// <param name="times">Times for verifying. Default value is AtLeastOnce if the times is not provided.</param>
 /// <typeparam name="TService">Mocked service type</typeparam>
 /// <returns></returns>
 public static SystemUnderTest VerifyCall <TService>(this SystemUnderTest sut,
                                                     Expression <Action <TService> > expression,
                                                     Times?times = null)
     where TService : class
 {
     sut.UseServiceMock <TService>(mock => mock.Verify(expression, times ?? Times.AtLeastOnce()));
     return(sut);
 }
Exemplo n.º 8
0
        public static void VerifyIgnoreArgs <T>(this Mock <T> mock,
                                                Expression <Action <T> > expression, Times?times = null)
            where T : class
        {
            expression = new MakeAnyVisitor().VisitAndConvert(
                expression, "VerifyIgnoreArgs");

            mock.Verify(expression, times ?? Times.AtLeastOnce());
        }
Exemplo n.º 9
0
        private void VerifyLogWrite(LogLevel level, Times?times = null)
        {
            times ??= Times.AtLeastOnce();

            _logWriter.Verify(writer => writer.Write(
                                  It.Is <LogContext>(context =>
                                                     context.Level == level &&
                                                     context.Sender == _sender),
                                  It.IsNotNull <JsonObject>()), times.Value);
        }
Exemplo n.º 10
0
        private void VerifyLogWriting(Times?times = null)
        {
            if (times == null)
            {
                times = Times.AtLeastOnce();
            }

            _logWriter.Verify(w => w.Write(
                                  It.IsAny <LogContext>(),
                                  It.IsAny <JsonObject>()), times.Value);
        }
Exemplo n.º 11
0
 /// <summary>
 /// Perform an assertion that GetAsync has been called upon the specified mock of repository.
 /// </summary>
 /// <typeparam name="T">Type of repository to mock.</typeparam>
 /// <typeparam name="TEntity">Type of entity to mock</typeparam>
 /// <param name="repository">Repository mock instance.</param>
 /// <param name="times">Number of times to check if called.</param>
 public static void VerifyGetAsyncCalled <T, TEntity>(this Mock <T> repository,
                                                      Times?times = null)
     where T : class, IDataReaderRepository
     where TEntity : class
 {
     if (times == null)
     {
         times = Times.AtLeastOnce();
     }
     repository.Verify(m => m.GetAsync(It.IsAny <Expression <Func <TEntity, bool> > >(), It.IsAny <Expression <Func <TEntity, object> > >(),
                                       It.IsAny <bool>()), times.Value);
 }
Exemplo n.º 12
0
        public void VerifyEmailSent(Times?times = null)
        {
            if (times == null)
            {
                times = Times.Once();
            }

            this.mock.Verify(s => s.SendEmailAsync(
                                 this.EmailToCheck,
                                 this.SubjectToCheck,
                                 this.MessageToCheck,
                                 this.AttachmentToCheck,
                                 this.type), times.Value);
        }
Exemplo n.º 13
0
        public void verify <T1>(Expression <Func <T1> > expression, Times?times = null)
        {
            var lambda     = (LambdaExpression)expression;
            var call       = (MethodCallExpression)lambda.Body;
            var mockObject = Expression.Lambda <Func <object> >(call.Object).Compile()();
            var method     = call.Method;
            var args       = call.Arguments;

            var mock     = this.GetMockFromObject(mockObject);
            var mockType = mock.GetType();

            var mockObjectInterface = this.GetInterfaceFromMock(mock);
            var helperDefinition    = this.GetType().GetMethods(BindingFlags.NonPublic | BindingFlags.Instance).First((m) => m.Name.StartsWith("VerifyHelper"));
            var helper = helperDefinition.MakeGenericMethod(mockObjectInterface);

            helper.Invoke(this, new object[] { mock, method, args, times == null ? Times.Once() : times.Value });
        }
Exemplo n.º 14
0
        public static Mock <ILogger> VerifyLogging(
            this Mock <ILogger> loggerMock,
            string expectedMessage,
            LogLevel expectedLogLevel = LogLevel.Debug,
            Times?times = null)
        {
            times ??= Times.Once();

            Func <object, Type, bool> state = (v, t) =>
                                              string.Compare(v.ToString(), expectedMessage, StringComparison.Ordinal) == 0;

            loggerMock.Verify(logger => logger.Log(
                                  It.Is <LogLevel>(l => l == expectedLogLevel),
                                  It.IsAny <EventId>(),
                                  It.Is <It.IsAnyType>((v, t) => state(v, t)),
                                  It.IsAny <Exception>(),
                                  It.Is <Func <It.IsAnyType, Exception, string> >((v, t) => true)), (Times)times);

            return(loggerMock);
        }
Exemplo n.º 15
0
        public static Mock <ILogger <T> > VerifyLogging <T>(this Mock <ILogger <T> > logger, string expectedMessage, LogLevel expectedLogLevel = LogLevel.Debug, Times?times = null)
        {
            if (times == null)
            {
                times = Times.Once();
            }

            Func <object, Type, bool> state = (v, t) => v.ToString().CompareTo(expectedMessage) == 0;

            logger.Verify(
                x => x.Log(
                    It.Is <LogLevel>(l => l == expectedLogLevel),
                    It.IsAny <EventId>(),
                    It.Is <It.IsAnyType>((v, t) => state(v, t)),
                    It.IsAny <Exception>(),
                    It.Is <Func <It.IsAnyType, Exception, string> >((v, t) => true)), (Times)times);

            return(logger);
        }
        /// <summary>
        /// Verifies that a specific invocation matching the given expression was performed on the mock.
        /// Use in conjunction with the default <see cref="MockBehavior.Loose" />.
        /// </summary>
        /// <typeparam name="TResult">Type of the return value. Typically omitted as it can be inferred from the expression.</typeparam>
        /// <param name="handler">The <see cref="HttpMessageHandler" /> mock.</param>
        /// <param name="expression">Lambda expression that specifies the method invocation.</param>
        /// <param name="times">
        /// Number of times that the invocation is expected to have occurred.
        /// If omitted, assumed to be <see cref="Times.AtLeastOnce" />.
        /// </param>
        /// <param name="failMessage">Message to include in the thrown <see cref="MockException" /> if verification fails.</param>
        /// <exception cref="MockException">The specified invocation did not occur (or did not occur the specified number of times).</exception>
        private static void Verify <TResult>(this Mock <HttpMessageHandler> handler, Expression <Func <IHttpMessageHandler, TResult> > expression, Times?times = null, string failMessage = null)
        {
            if (handler == null)
            {
                throw new ArgumentNullException(nameof(handler));
            }

            handler.Protected().As <IHttpMessageHandler>().Verify(expression, times, failMessage);
        }
Exemplo n.º 17
0
        public static Mock <ILogger <T> > VerifyLogging <T>(this Mock <ILogger <T> > logger, LogLevel level, Times?times = null)
        {
            times ??= Times.AtLeastOnce();

            logger.Verify(
                x => x.Log(
                    It.Is <LogLevel>(l => l == level),
                    It.IsAny <EventId>(),
                    It.Is <It.IsAnyType>((v, t) => true),
                    It.IsAny <Exception>(),
                    It.Is <Func <It.IsAnyType, Exception, string> >((v, t) => true)), (Times)times);

            return(logger);
        }
Exemplo n.º 18
0
 public void AssertLoadAsyncInvoked(Expression <Func <string, bool> > match, Times?times = null)
 {
     _mock.Verify(x => x.LoadAsync(It.Is(match)), times ?? Times.Once());
 }
Exemplo n.º 19
0
 public void AssertLoadAsyncInvoked(Times?times = null)
 {
     _mock.Verify(x => x.LoadAsync(It.IsAny <string>()), times ?? Times.Once());
 }
Exemplo n.º 20
0
        /// <summary>
        /// Verifies that an event of type <typeparam name="T"></typeparam> has been published with the IBigBrother mock
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="mock">Instance of Mock&lt;IBigBrother&gt;</param>
        /// <param name="eventVerifyPredicate">(Optional) The predicate to match the event</param>
        /// <param name="times">Verify the number of times a method is allowed to be called</param>
        public static void VerifyPublish <T>(this Mock <IBigBrother> mock, Expression <Func <T, bool> > eventVerifyPredicate = null, Times?times = null)
            where T : TelemetryEvent
        {
            var timesInternal = times ?? Times.Once();

            if (eventVerifyPredicate != null)
            {
                mock.Verify(call => call.Publish <T>(It.Is <T>(eventVerifyPredicate), It.IsAny <string>(), It.IsAny <string>(), It.IsAny <int>()), timesInternal);
            }
            else
            {
                mock.Verify(call => call.Publish <T>(It.IsAny <T>(), It.IsAny <string>(), It.IsAny <string>(), It.IsAny <int>()), timesInternal);
            }
        }
Exemplo n.º 21
0
 public static Mock <ILogger <T> > VerifyLogging <T>(this Mock <ILogger <T> > logger, LogLevel expectedLogLevel = LogLevel.Debug, Times?times = null)
 {
     return(logger.VerifyLogging(null, false, expectedLogLevel, times));
 }
Exemplo n.º 22
0
 /// <summary>
 /// Verify GetFromManifestAsync.
 /// </summary>
 /// <param name="bundle">The bundle to verify against.</param>
 /// <param name="times">Number of times to verify GetFromManifestAsync.</param>
 protected void VerifyGetFromManifest(string bundle, Times?times = null)
 {
     ManifestServiceMock.Verify(x => x.GetFromManifestAsync(bundle), times ?? Times.Once());
 }
Exemplo n.º 23
0
 public void VerifySetInvoked(string id, bool favourite, Times?times = null)
 {
     _favouriteManager.Verify(x => x.Set(id, favourite), times ?? Times.Once());
 }
Exemplo n.º 24
0
 public void AssertOpenFileInvoked(Expression <Func <OpenFileDialogOptions, bool> > match, Times?times = null)
 {
     _mock.Verify(x => x.OpenFile(It.Is(match)), times ?? Times.Once());
 }
Exemplo n.º 25
0
        public static void Verify <Item, Score>(Mock <IScorable <Item, Score> > mock, Item item, CancellationToken token, Times prepare, Times hasScore, Times getScore, Times post, Times?done = null)
        {
            done = done ?? prepare;

            mock.Verify(s => s.PrepareAsync(item, token), prepare);
            mock.Verify(s => s.HasScore(item, It.IsAny <object>()), hasScore);
            mock.Verify(s => s.GetScore(item, It.IsAny <object>()), getScore);
            mock.Verify(s => s.PostAsync(item, It.IsAny <object>(), token), post);
            mock.Verify(s => s.DoneAsync(item, It.IsAny <object>(), token), done.Value);
        }
Exemplo n.º 26
0
 public static void VerifyLogger <T>(Mock <ILogger <T> > loggerMock, LogLevel logLevel, Times?times = null)
 {
     if (times == null)
     {
         times = Times.Once();
     }
     loggerMock.Verify(x => x.Log(logLevel,
                                  It.IsAny <EventId>(),
                                  It.IsAny <It.IsAnyType>(),
                                  It.IsAny <Exception>(),
                                  (Func <It.IsAnyType, Exception, string>)It.IsAny <object>()), times.Value);
 }
Exemplo n.º 27
0
 public static void ShouldHaveReceived <T>(
     this Mock <T> mock,
     Expression <Action <T> > expression,
     Times?times = null)
     where T : class
 => mock.Verify(expression, times ?? Times.Once());
Exemplo n.º 28
0
 public static void ShouldHaveReceivedSet <T>(
     this Mock <T> mock,
     Action <T> setterExpression,
     Times?times = null)
     where T : class
 => mock.VerifySet(setterExpression, times ?? Times.Once());
Exemplo n.º 29
0
 public static Mock <ILogger <T> > VerifyLogError <T>(
     this Mock <ILogger <T> > logger,
     Exception exception,
     string expectedMessage,
     Times?times = null) => VerifyLogging(logger, exception, expectedMessage, LogLevel.Error, times);
Exemplo n.º 30
0
        public static Mock <ILogger <T> > VerifyEventIdWasCalled <T>(this Mock <ILogger <T> > logger, EventId eventId, Times?times = null)
        {
            times ??= Times.Once();

            logger.Verify(
                x => x.Log(
                    It.IsAny <LogLevel>(),
                    eventId,
                    It.Is <It.IsAnyType>((v, t) => true),
                    It.IsAny <Exception>(),
                    It.Is <Func <It.IsAnyType, Exception, string> >((v, t) => true)), times.Value);

            return(logger);
        }