Beispiel #1
0
 internal static IReturnsResult <TMock> ReturnsUsingContext <TMock, TResult>(this IReturns <TMock, TResult> setup,
                                                                             ISpecimenContext context)
     where TMock : class
 {
     return(setup.Returns(() =>
     {
         var result = (TResult)context.Resolve(typeof(TResult));
         setup.Returns(result);
         return result;
     }));
 }
Beispiel #2
0
        public static IReturnsResult <TMock> Returns <TMock, TResult>(this IReturns <TMock, TResult> returns, Func <int, TResult> valueFunction)
            where TMock : class
        {
            int callCount = 0;

            return(returns.Returns(() => valueFunction(++callCount)));
        }
        public static IReturnsResult <TMock> ReturnDbSetAsync <TMock, TResult, TEntity>(
            this IReturns <TMock, TResult> fluent,
            IList <TEntity> sourceList)
            where TMock : class
            where TResult : DbSet <TEntity>
            where TEntity : class
        {
            var data = sourceList.AsQueryable();

            var mockSet = new Mock <DbSet <TEntity> >();

            mockSet.As <IDbAsyncEnumerable <TEntity> >()
            .Setup(m => m.GetAsyncEnumerator())
            .Returns(new TestDbAsyncEnumerator <TEntity>(data.GetEnumerator()));

            mockSet.As <IQueryable <TEntity> >()
            .Setup(m => m.Provider)
            .Returns(new TestDbAsyncQueryProvider <TEntity>(data.Provider));

            mockSet.As <IQueryable <TEntity> >().Setup(m => m.Expression).Returns(data.Expression);
            mockSet.As <IQueryable <TEntity> >().Setup(m => m.ElementType).Returns(data.ElementType);
            mockSet.As <IQueryable <TEntity> >().Setup(m => m.GetEnumerator()).Returns(data.GetEnumerator());

            return(fluent.Returns((TResult)mockSet.Object));
        }
Beispiel #4
0
        /// <summary>
        ///     Throws the specified exception for the specified <see cref="Task" />
        /// </summary>
        public static IReturnsResult <TMock> ThrowsAsync <TMock>(this IReturns <TMock, Task> mock, Exception exception) where TMock : class
        {
            var completionSource = new TaskCompletionSource <bool>();

            completionSource.SetException(exception);
            return(mock.Returns(completionSource.Task));
        }
        public static IReturnsResult <TMock> ReturnsValueProviderResult <TMock>(this IReturns <TMock, ValueProviderResult> returns, object rawValue)
            where TMock : class
        {
            var result = new ValueProviderResult(rawValue, rawValue.ToString(), CultureInfo.InvariantCulture);

            return(returns.Returns(result));
        }
Beispiel #6
0
        /// <summary>
        /// Specifies the exception to throw when the asynchronous method is invoked.
        /// </summary>
        /// <typeparam name="TMock">Mocked type.</typeparam>
        /// <typeparam name="TResult">Type of the return value.</typeparam>
        /// <param name="mock">Returns verb which represents the mocked type and the task of return type</param>
        /// <param name="exception">Exception instance to throw.</param>
        public static IReturnsResult <TMock> ThrowsAsync <TMock, TResult>(this IReturns <TMock, Task <TResult> > mock, Exception exception) where TMock : class
        {
            var tcs = new TaskCompletionSource <TResult>();

            tcs.SetException(exception);

            return(mock.Returns(tcs.Task));
        }
        /// <summary>
        /// Allows to specify the return value of an asynchronous method.
        /// </summary>
        public static IReturnsResult <TMock> ReturnsAsync <TMock, TResult>(this IReturns <TMock, Task <TResult> > mock, TResult value) where TMock : class
        {
            var tcs = new TaskCompletionSource <TResult>();

            tcs.SetResult(value);

            return(mock.Returns(tcs.Task));
        }
Beispiel #8
0
        public static IReturnsResult <TContext> ReturnsDbSet <TEntity, TContext>(this IReturns <TContext, DbSet <TEntity> > setup, IQueryable <TEntity> entities, bool isAsync = false)
            where TEntity : class
            where TContext : DbContext
        {
            var mockSet = CreateMockSet(entities, isAsync);

            return(setup.Returns(mockSet.Object));
        }
        public static TaskCompletionSource <R> WaitsForSignal <T, R>(this IReturns <T, Task <R> > self)
            where T : class
        {
            var tcs = new TaskCompletionSource <R>();

            self.Returns(tcs.Task);
            return(tcs);
        }
Beispiel #10
0
        public static IReturnsResult <TMock> Returns <TMock>(this IReturns <TMock, IPromise <DataType> > mock, DataType type)
            where TMock : class
        {
            var promise = new AcyclicPromise <DataType>();

            promise.BeginFulfilling();
            promise.Fulfill(type);
            return(mock.Returns(promise));
        }
Beispiel #11
0
 public static IReturnsResult <TContext> ReturnsDbSet <TEntity, TContext>(
     this IReturns <TContext, DbSet <TEntity> > setup,
     IEnumerable <TEntity> entities, out Mock <DbSet <TEntity> > mockSet)
     where TEntity : class
     where TContext : DbContext
 {
     mockSet = CreateMockSet(entities.AsQueryable());
     return(setup.Returns(mockSet.Object));
 }
Beispiel #12
0
 /// <summary>
 /// Specifies the exception to throw when the asynchronous method is invoked.
 /// </summary>
 /// <typeparam name="TMock">Mocked type.</typeparam>
 /// <param name="mock">Returns verb which represents the mocked type and the task return type</param>
 /// <param name="exception">Exception instance to throw.</param>
 public static IReturnsResult <TMock> ThrowsAsync <TMock>(this IReturns <TMock, Task> mock, Exception exception) where TMock : class
 {
     return(mock.Returns(() =>
     {
         var tcs = new TaskCompletionSource <bool>();
         tcs.SetException(exception);
         return tcs.Task;
     }));
 }
Beispiel #13
0
        public static IReturnsResult <TContext> ReturnsDbSet <TEntity, TContext>(
            this IReturns <TContext, DbSet <TEntity> > setup, TEntity[] entities)
            where TEntity : class
            where TContext : DbContext
        {
            var mockSet = CreateMockSet(entities.AsQueryable());

            return(setup.Returns(mockSet.Object));
        }
Beispiel #14
0
        public static IReturnsResult <TContext> ReturnsDbSet <TEntity, TContext>(
            this IReturns <TContext, IDbSet <TEntity> > setup,
            TEntity entity)
            where TEntity : Entity
            where TContext : DbContext
        {
            var mockSet = CreateMockSet(new[] { entity }.AsQueryable());

            return(setup.Returns(mockSet.Object));
        }
Beispiel #15
0
        public static IReturnsResult <TContext> ReturnsDbSet <TEntity, TContext>(
            this IReturns <TContext, DbSet <TEntity> > setup,
            IQueryable <TEntity> entities)
            where TEntity : class
            where TContext : DbContext
        {
            var mockSet = SetUpDbSet(entities);

            return(setup.Returns(mockSet.Object));
        }
Beispiel #16
0
        public static IReturnsResult <TContext> ReturnsDbSetAsync <TEntity, TContext>(
            this IReturns <TContext, DbSet <TEntity> > setup,
            IEnumerable <TEntity> entities)
            where TEntity : class
            where TContext : DbContext
        {
            var mockSet = MockAsyncData <TEntity> .MockAsyncQueryResult(entities.AsQueryable());

            return(setup.Returns(mockSet.Object));
        }
Beispiel #17
0
        private static IReturnsResult <TMock> DelayedResult <TMock, TResult>(IReturns <TMock, ValueTask <TResult> > mock,
                                                                             TResult value, TimeSpan delay)
            where TMock : class
        {
            Guard.Positive(delay);

            return(mock.Returns(() =>
            {
                return new ValueTask <TResult>(Task.Delay(delay).ContinueWith(t => value));
            }));
        }
Beispiel #18
0
        public static IReturnsResult <TContext> ReturnsDbSetAsync <TEntity, TContext>(
            this IReturns <TContext, DbSet <TEntity> > setup,
            IEnumerable <TEntity> entities)
            where TEntity : class
            where TContext : class
        {
            var mockSet = CreateMockDbSetForAsync(entities);

            MockDbSets[typeof(TEntity)] = mockSet;
            return(setup.Returns(mockSet.Object));
        }
Beispiel #19
0
 public static IReturnsResult <TMock> CallbackAsync <T1, T2, T3, T4, T5, TMock>(
     this IReturns <TMock, Task> mock,
     Action <T1, T2, T3, T4, T5> callback)
     where TMock : class
 {
     return(mock.Returns <T1, T2, T3, T4, T5>(
                (t1, t2, t3, t4, t5) =>
     {
         callback(t1, t2, t3, t4, t5);
         return TaskHelper.CompletedTask;
     }));
 }
Beispiel #20
0
 public static IReturnsResult <TMock> CallbackAsync <T1, TMock>(
     this IReturns <TMock, Task> mock,
     Action <T1> callback)
     where TMock : class
 {
     return(mock.Returns <T1>(
                t1 =>
     {
         callback(t1);
         return TaskHelper.CompletedTask;
     }));
 }
Beispiel #21
0
 public static IReturnsResult <TMock> CallbackAsync <T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, TMock>(
     this IReturns <TMock, Task> mock,
     Action <T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16> callback)
     where TMock : class
 {
     return(mock.Returns <T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16>(
                (t1, t2, t3, t4, t5, t6, t7, t8, t9, t10, t11, t12, t13, t14, t15, t16) =>
     {
         callback(t1, t2, t3, t4, t5, t6, t7, t8, t9, t10, t11, t12, t13, t14, t15, t16);
         return TaskHelper.CompletedTask;
     }));
 }
Beispiel #22
0
        private static IReturnsResult <TMock> DelayedException <TMock, TResult>(IReturns <TMock, Task <TResult> > mock,
                                                                                Exception exception, TimeSpan delay)
            where TMock : class
        {
            GuardPositiveDelay(delay);

            var tcs = new TaskCompletionSource <TResult>();

            Task.Delay(delay).ContinueWith(t => tcs.SetException(exception));

            return(mock.Returns(tcs.Task));
        }
Beispiel #23
0
        private static IReturnsResult <TMock> DelayedResult <TMock, TResult>(IReturns <TMock, ValueTask <TResult> > mock,
                                                                             TResult value, TimeSpan delay)
            where TMock : class
        {
            Guard.Positive(delay);

            var tcs = new TaskCompletionSource <TResult>();

            Task.Delay(delay).ContinueWith(t => tcs.SetResult(value));

            return(mock.Returns(new ValueTask <TResult>(tcs.Task)));
        }
Beispiel #24
0
        internal static IReturnsResult <TMock> ReturnsUsingContext <TMock, TResult>(IReturns <TMock, TResult> setup,
                                                                                    ISpecimenContext context)
            where TMock : class
        {
            return(setup.Returns(() =>
            {
                var specimen = context.Resolve(typeof(TResult));


                // check if specimen is null but member is non-nullable value type
                if (specimen == null && (default(TResult) != null))
                {
                    throw new InvalidOperationException(
                        string.Format(
                            CultureInfo.CurrentCulture,
                            "Tried to setup a member with a return type of {0}, but null was found instead.",
                            typeof(TResult)));
                }


                // check if specimen can be safely converted to TResult
                if (specimen != null && !(specimen is TResult))
                {
                    throw new InvalidOperationException(
                        string.Format(
                            CultureInfo.CurrentCulture,
                            "Tried to setup a member with a return type of {0}, but an instance of {1} was found instead.",
                            typeof(TResult),
                            specimen.GetType()));
                }


                TResult result = (TResult)specimen;


                //"cache" value for future invocations
                setup.Returns(result);
                return result;
            }));
        }
Beispiel #25
0
        public static IReturnsResult <TMock> ReturnsAsEmptyDbSetAsync <TMock, TItem>(
            this IReturns <TMock, Task <IQueryable <TItem> > > mock)
            where TMock : class
            where TItem : class
        {
            var dbSetMock  = new Mock <DbSet <TItem> >();
            var collection = new List <TItem>().AsQueryable();

            dbSetMock.SetupAsQueryable(collection);

            var completionSource = new TaskCompletionSource <IQueryable <TItem> >();

            completionSource.SetResult(dbSetMock.Object);
            return(mock.Returns(completionSource.Task));
        }
        /// <summary>
        /// Sets up a response for SendAsync
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="mock"></param>
        /// <param name="statusCode">The response status code</param>
        /// <param name="responseBody">Object to be rendered as Json in the response body</param>
        /// <returns></returns>
        public static IReturnsResult <TestableHttpMessageHandler> RespondsWith <T>(this IReturns <TestableHttpMessageHandler, Task <HttpResponseMessage> > mock,
                                                                                   HttpStatusCode statusCode, T responseBody)
        => mock.Returns(async(HttpRequestMessage request, CancellationToken token) => {
            var response = request.CreateResponse(statusCode);

            if (responseBody != null)
            {
                // Convert the input object into a stream and use this stream as the reponse's content.
                // This simulates real Http responses and helps detect deserialisation errors early

                var objectContent = new ObjectContent <T>(responseBody, new JsonMediaTypeFormatter());
                var stream        = await objectContent.ReadAsStreamAsync();

                var streamContent = new StreamContent(stream);
                streamContent.Headers.ContentType = objectContent.Headers.ContentType;

                response.Content = streamContent;
            }

            return(response);
        });
Beispiel #27
0
 public static IReturnsResult <TMock> CompletesWith <TMock, TRet>(this IReturns <TMock, Task <TRet> > self, TRet value)
     where TMock : class
 {
     return(self.Returns(Task.FromResult(value)));
 }
Beispiel #28
0
 public static IReturnsResult <TMock> Completes <TMock>(this IReturns <TMock, Task> self)
     where TMock : class
 {
     return(self.Returns(Task.FromResult((object)null)));
 }
Beispiel #29
0
 public static IReturnsResult <TMock> CompletesWithNull <TMock, TRet>(this IReturns <TMock, Task <TRet> > self)
     where TMock : class
     where TRet : class
 {
     return(self.Returns(Task.FromResult((TRet)null)));
 }
Beispiel #30
0
 // Helper to get around Mock Returns((Type)null) weirdness.
 public static IReturnsResult <TMock> ReturnsNull <TMock, TRet>(this IReturns <TMock, TRet> self)
     where TMock : class
     where TRet : class
 {
     return(self.Returns((TRet)null));
 }