├── GitInfo.txt ├── .github ├── FUNDING.yml └── workflows │ ├── sponsor.yml │ └── includes.yml ├── Moq.snk ├── moq.png ├── moq-bigger.png ├── moq-icon.png ├── moq-small.png ├── docs ├── Gemfile ├── _sass │ ├── utility │ │ ├── max-width.scss │ │ ├── text-alignment.scss │ │ ├── padding.scss │ │ ├── margin.scss │ │ ├── width.scss │ │ ├── position.scss │ │ ├── height.scss │ │ ├── flex.scss │ │ └── space-between.scss │ └── reset.scss ├── assets │ ├── images │ │ ├── moq-icon.png │ │ └── github-32.png │ └── main.scss ├── user-guide │ └── index.md ├── _config.yml ├── _layouts │ ├── default.html │ └── homepage.html ├── index.md ├── _includes │ ├── head.html │ └── header.html └── Gemfile.lock ├── .gitignore ├── .gitattributes ├── tests ├── Moq.Tests.ComTypes │ ├── Moq.Tests.ComTypes.dll │ ├── BuildDLLFromIDL.cmd │ ├── ComTypes.idl │ └── README.md ├── Moq.Tests.FSharpTypes │ ├── IHasIndexer.fs │ ├── IHasProperty.fs │ ├── HasAbstractIndexer.fs │ ├── HasAbstractProperty.fs │ ├── IHasActionEvent.fs │ ├── IHasEventHandlerEvent.fs │ ├── HasAbstractActionEvent.fs │ ├── HasActionEvent.fs │ ├── HasAbstractEventHandlerEvent.fs │ ├── HasProperty.fs │ ├── HasIndexer.fs │ └── Moq.Tests.FSharpTypes.fsproj ├── Moq.Tests │ ├── StringExtensions.cs │ ├── ReflectionExtensions.cs │ ├── Async │ │ └── AwaitableFixture.cs │ ├── RecordsFixture.cs │ ├── HidePropertyFixture.cs │ ├── Regressions │ │ ├── StreamFixture.cs │ │ └── FluentMockIssues.cs │ ├── CaptureMatchFixture.cs │ ├── CallBaseFixture.cs │ ├── IsValueTypeFixture.cs │ ├── IsSubtypeFixture.cs │ ├── UnmatchableMatchersFixture.cs │ ├── Matchers │ │ ├── AnyMatcherFixture.cs │ │ └── ParamArrayMatcherFixture.cs │ ├── SetupsFixture.cs │ ├── StringBuilderExtensionsFixture.cs │ ├── InterceptorFixture.cs │ ├── SequentialActionExtensionsFixture.cs │ ├── DefaultValueProviderFixture.cs │ ├── EventHandlerTypesMustMatchFixture.cs │ ├── OccurrenceFixture.cs │ ├── MockedFixture.cs │ ├── MethodExpectationFixture.cs │ ├── CustomMatcherFixture.cs │ ├── Moq.Tests.csproj │ ├── AfterReturnCallbackDelegateValidationFixture.cs │ └── ProxyFactories │ │ └── MostSpecificOverrideFixture.cs └── Moq.Tests.VisualBasic │ └── Moq.Tests.VisualBasic.vbproj ├── Before.Moq.sln.targets ├── src └── Moq │ ├── Behavior.cs │ ├── IMatcher.cs │ ├── Behaviors │ ├── NoOp.cs │ ├── ReturnBase.cs │ ├── ReturnValue.cs │ ├── ThrowException.cs │ ├── Callback.cs │ ├── ReturnComputedValue.cs │ ├── ThrowComputedException.cs │ ├── VerifyInvocationCount.cs │ └── RaiseEvent.cs │ ├── MockExceptionReasons.cs │ ├── Language │ ├── Flow │ │ ├── IThrowsResult.cs │ │ ├── ICallBaseResult.cs │ │ ├── IReturnsResult.cs │ │ ├── ICallbackResult.cs │ │ ├── SetterSetupPhrase.cs │ │ ├── IReturnsThrows.cs │ │ ├── ISetup.cs │ │ └── WhenPhrase.cs │ ├── ICallBase.cs │ ├── GenericTypeParameters.tt │ ├── ICallbackSetter.cs │ ├── ICallbackGetter.cs │ ├── IRaise.tt │ ├── ISetupSequentialResult.cs │ ├── ISetupConditionResult.cs │ ├── IRaise.cs │ ├── IReturnsGetter.cs │ ├── IReturns.tt │ ├── IThrows.tt │ ├── ISetupSequentialAction.cs │ └── IVerifies.cs │ ├── ISetupList.cs │ ├── Interception │ ├── IInterceptor.cs │ ├── IProxy.cs │ ├── Mock.cs │ └── ProxyFactory.cs │ ├── IInvocationList.cs │ ├── Condition.cs │ ├── Range.cs │ ├── Matchers │ ├── AnyMatcher.cs │ ├── ExpressionMatcher.cs │ ├── LazyEvalMatcher.cs │ ├── RefMatcher.cs │ ├── ConstantMatcher.cs │ └── ParamArrayMatcher.cs │ ├── Obsolete │ ├── MockExtensions.cs │ ├── SequenceExtensions.cs │ └── IOccurrence.cs │ ├── MethodSetup.cs │ ├── Async │ ├── IAwaitableFactory.cs │ ├── Awaitable.cs │ ├── ValueTaskFactory.cs │ ├── TaskFactory.cs │ ├── AwaitExpression.cs │ ├── TaskFactory`1.cs │ ├── ValueTaskFactory`1.cs │ ├── AwaitableFactory.cs │ ├── AwaitableFactory`1.cs │ └── AwaitableFactory`2.cs │ ├── DefaultExpressionCompiler.cs │ ├── Expressions │ └── Visitors │ │ ├── Apply.cs │ │ ├── EvaluateCaptures.cs │ │ └── ConstructorCallVisitor.cs │ ├── MockBehavior.cs │ ├── MockExtensions.cs │ ├── IMocked.cs │ ├── Properties │ └── AssemblyInfo.cs │ ├── Switches.cs │ ├── MatchExpression.cs │ ├── ITypeMatcher.cs │ ├── Pair.cs │ ├── ParameterTypes.cs │ ├── Protected │ └── ProtectedExtension.cs │ ├── InvocationFunc.cs │ ├── InvocationAction.cs │ ├── ImmutablePopOnlyStack.cs │ ├── IMock.cs │ ├── Expectation.cs │ ├── IInvocation.cs │ ├── ExpressionReconstructor.cs │ ├── InnerMockSetup.cs │ ├── EventHandlerCollection.cs │ ├── CaptureMatch.cs │ ├── DefaultValue.cs │ ├── SequenceSetup.cs │ ├── MockSequence.cs │ ├── MockDefaultValueProvider.cs │ ├── SetupWithOutParameterSupport.cs │ ├── EmptyDefaultValueProvider.cs │ ├── TypeMatcherAttribute.cs │ ├── AsInterface.cs │ ├── ExpressionCompiler.cs │ ├── Linq │ ├── MockQuery.cs │ └── Mock.cs │ └── Capture.cs ├── Directory.Build.props ├── .editorconfig ├── README.md ├── .netconfig ├── appveyor.yml └── License.txt /GitInfo.txt: -------------------------------------------------------------------------------- 1 | 4.19.0 2 | -------------------------------------------------------------------------------- /.github/FUNDING.yml: -------------------------------------------------------------------------------- 1 | github: devlooped 2 | -------------------------------------------------------------------------------- /Moq.snk: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/stakx/moq/HEAD/Moq.snk -------------------------------------------------------------------------------- /moq.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/stakx/moq/HEAD/moq.png -------------------------------------------------------------------------------- /moq-bigger.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/stakx/moq/HEAD/moq-bigger.png -------------------------------------------------------------------------------- /moq-icon.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/stakx/moq/HEAD/moq-icon.png -------------------------------------------------------------------------------- /moq-small.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/stakx/moq/HEAD/moq-small.png -------------------------------------------------------------------------------- /docs/Gemfile: -------------------------------------------------------------------------------- 1 | source 'https://rubygems.org' 2 | 3 | gem 'jekyll-relative-links' 4 | -------------------------------------------------------------------------------- /docs/_sass/utility/max-width.scss: -------------------------------------------------------------------------------- 1 | .max-w-650 { 2 | max-width: 650px; 3 | } 4 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | out 2 | bin 3 | obj 4 | *.suo 5 | *.user 6 | *.cache 7 | .vs 8 | */**/.* 9 | -------------------------------------------------------------------------------- /.gitattributes: -------------------------------------------------------------------------------- 1 | # Auto detect text files and perform LF normalization 2 | * text=auto -------------------------------------------------------------------------------- /docs/_sass/utility/text-alignment.scss: -------------------------------------------------------------------------------- 1 | .text-center { 2 | text-align: center; 3 | } 4 | -------------------------------------------------------------------------------- /docs/assets/images/moq-icon.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/stakx/moq/HEAD/docs/assets/images/moq-icon.png -------------------------------------------------------------------------------- /docs/assets/images/github-32.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/stakx/moq/HEAD/docs/assets/images/github-32.png -------------------------------------------------------------------------------- /docs/user-guide/index.md: -------------------------------------------------------------------------------- 1 | --- 2 | --- 3 | 4 | # User Guide 5 | 6 | This is work in progress and currently under construction. 7 | -------------------------------------------------------------------------------- /docs/_sass/utility/padding.scss: -------------------------------------------------------------------------------- 1 | .p { 2 | 3 | &x-8 { 4 | padding-left: 4px; 5 | padding-right: 4px; 6 | } 7 | } 8 | -------------------------------------------------------------------------------- /tests/Moq.Tests.ComTypes/Moq.Tests.ComTypes.dll: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/stakx/moq/HEAD/tests/Moq.Tests.ComTypes/Moq.Tests.ComTypes.dll -------------------------------------------------------------------------------- /docs/_sass/utility/margin.scss: -------------------------------------------------------------------------------- 1 | .mx-auto { 2 | margin-left: auto; 3 | margin-right: auto; 4 | } 5 | 6 | .my-36 { 7 | margin-top: 36px; 8 | margin-bottom: 36px; 9 | } 10 | -------------------------------------------------------------------------------- /docs/_sass/utility/width.scss: -------------------------------------------------------------------------------- 1 | .w { 2 | 3 | &-full { 4 | width: 100%; 5 | } 6 | 7 | &-24 { 8 | width: 24px; 9 | } 10 | 11 | &-42 { 12 | width: 42px; 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /docs/_sass/utility/position.scss: -------------------------------------------------------------------------------- 1 | .absolute { 2 | position: absolute; 3 | } 4 | 5 | .relative { 6 | position: relative; 7 | } 8 | 9 | .sticky { 10 | position: sticky; 11 | } 12 | 13 | .top-0 { 14 | top: 0; 15 | } 16 | -------------------------------------------------------------------------------- /Before.Moq.sln.targets: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | -------------------------------------------------------------------------------- /docs/_config.yml: -------------------------------------------------------------------------------- 1 | baseurl: /moq 2 | 3 | defaults: 4 | - scope: 5 | path: "" 6 | values: 7 | layout: "default" 8 | - scope: 9 | path: "index.md" 10 | values: 11 | layout: "homepage" 12 | 13 | plugins: 14 | - jekyll-relative-links 15 | -------------------------------------------------------------------------------- /docs/_sass/utility/height.scss: -------------------------------------------------------------------------------- 1 | .h { 2 | 3 | &-full { 4 | height: 100%; 5 | } 6 | 7 | &-24 { 8 | height: 24px; 9 | } 10 | 11 | &-42 { 12 | height: 42px; 13 | } 14 | 15 | &-64 { 16 | height: 64px; 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /tests/Moq.Tests.ComTypes/BuildDLLFromIDL.cmd: -------------------------------------------------------------------------------- 1 | midl /mktyplib203 /env win32 /tlb ComTypes.tlb ComTypes.idl 2 | tlbimp ComTypes.tlb /out:Moq.Tests.ComTypes.dll /namespace:Moq.Tests.ComTypes /keyfile:..\..\Moq.snk /asmversion:4.0.0.0 3 | peverify Moq.Tests.ComTypes.dll 4 | del ComTypes.tlb 5 | -------------------------------------------------------------------------------- /docs/_layouts/default.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | {% include head.html %} 4 | 5 | {% include header.html %} 6 |
7 | {{ content }} 8 |
9 | 10 | 11 | -------------------------------------------------------------------------------- /docs/index.md: -------------------------------------------------------------------------------- 1 | --- 2 | --- 3 | 4 | ![](assets/images/moq-icon.png) 5 | 6 | Welcome to the documentation for version 4 of [stakx](https://github/stakx)' fork of Moq! 7 | 8 | [Quickstart for the parent project](https://github.com/moq/moq/wiki/Quickstart) \| [User Guide](user-guide/index.md) 9 | -------------------------------------------------------------------------------- /docs/_layouts/homepage.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | {% include head.html %} 4 | 5 | {% include header.html %} 6 |
7 | {{ content }} 8 |
9 | 10 | 11 | -------------------------------------------------------------------------------- /docs/_sass/utility/flex.scss: -------------------------------------------------------------------------------- 1 | .flex { 2 | display: flex; 3 | 4 | &-grow { 5 | flex-grow: 1; 6 | } 7 | } 8 | 9 | .items { 10 | 11 | &-center { 12 | align-items: center; 13 | } 14 | } 15 | 16 | .justify { 17 | 18 | &-stretch { 19 | justify-content: stretch; 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /docs/_sass/utility/space-between.scss: -------------------------------------------------------------------------------- 1 | .space-x { 2 | 3 | &-4 > * + * { 4 | margin-left: 4px; 5 | } 6 | 7 | &-8 > * + * { 8 | margin-left: 8px; 9 | } 10 | 11 | &-12 > * + * { 12 | margin-left: 12px; 13 | } 14 | 15 | &-16 > * + * { 16 | margin-left: 16px; 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /tests/Moq.Tests.FSharpTypes/IHasIndexer.fs: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2007, Clarius Consulting, Manas Technology Solutions, InSTEDD, and Contributors. 2 | // All rights reserved. Licensed under the BSD 3-Clause License; see License.txt. 3 | 4 | namespace Moq.Tests.FSharpTypes 5 | 6 | open System; 7 | 8 | type IHasIndexer = 9 | abstract member Item: int -> obj with get, set 10 | -------------------------------------------------------------------------------- /tests/Moq.Tests.FSharpTypes/IHasProperty.fs: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2007, Clarius Consulting, Manas Technology Solutions, InSTEDD, and Contributors. 2 | // All rights reserved. Licensed under the BSD 3-Clause License; see License.txt. 3 | 4 | namespace Moq.Tests.FSharpTypes 5 | 6 | open System; 7 | 8 | type IHasProperty = 9 | abstract member Property: obj with get, set 10 | -------------------------------------------------------------------------------- /src/Moq/Behavior.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2007, Clarius Consulting, Manas Technology Solutions, InSTEDD, and Contributors. 2 | // All rights reserved. Licensed under the BSD 3-Clause License; see License.txt. 3 | 4 | namespace Moq 5 | { 6 | internal abstract class Behavior 7 | { 8 | protected Behavior() 9 | { 10 | } 11 | 12 | public abstract void Execute(Invocation invocation); 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /tests/Moq.Tests.FSharpTypes/HasAbstractIndexer.fs: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2007, Clarius Consulting, Manas Technology Solutions, InSTEDD, and Contributors. 2 | // All rights reserved. Licensed under the BSD 3-Clause License; see License.txt. 3 | 4 | namespace Moq.Tests.FSharpTypes 5 | 6 | open System; 7 | 8 | [] 9 | type HasAbstractIndexer() = 10 | abstract Item: int -> obj with get, set 11 | -------------------------------------------------------------------------------- /tests/Moq.Tests.FSharpTypes/HasAbstractProperty.fs: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2007, Clarius Consulting, Manas Technology Solutions, InSTEDD, and Contributors. 2 | // All rights reserved. Licensed under the BSD 3-Clause License; see License.txt. 3 | 4 | namespace Moq.Tests.FSharpTypes 5 | 6 | open System; 7 | 8 | [] 9 | type HasAbstractProperty() = 10 | abstract Property: obj with get, set 11 | -------------------------------------------------------------------------------- /tests/Moq.Tests.FSharpTypes/IHasActionEvent.fs: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2007, Clarius Consulting, Manas Technology Solutions, InSTEDD, and Contributors. 2 | // All rights reserved. Licensed under the BSD 3-Clause License; see License.txt. 3 | 4 | namespace Moq.Tests.FSharpTypes 5 | 6 | open System; 7 | 8 | type IHasActionEvent = 9 | [] 10 | abstract member Event: IDelegateEvent 11 | -------------------------------------------------------------------------------- /tests/Moq.Tests.FSharpTypes/IHasEventHandlerEvent.fs: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2007, Clarius Consulting, Manas Technology Solutions, InSTEDD, and Contributors. 2 | // All rights reserved. Licensed under the BSD 3-Clause License; see License.txt. 3 | 4 | namespace Moq.Tests.FSharpTypes 5 | 6 | open System; 7 | 8 | type IHasEventHandlerEvent = 9 | [] 10 | abstract member Event: IEvent 11 | -------------------------------------------------------------------------------- /tests/Moq.Tests.FSharpTypes/HasAbstractActionEvent.fs: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2007, Clarius Consulting, Manas Technology Solutions, InSTEDD, and Contributors. 2 | // All rights reserved. Licensed under the BSD 3-Clause License; see License.txt. 3 | 4 | namespace Moq.Tests.FSharpTypes 5 | 6 | open System; 7 | 8 | [] 9 | type HasAbstractActionEvent = 10 | [] 11 | abstract member Event: IDelegateEvent 12 | -------------------------------------------------------------------------------- /docs/_sass/reset.scss: -------------------------------------------------------------------------------- 1 | *, 2 | *::before, 3 | *::after { 4 | box-sizing: border-box; 5 | } 6 | 7 | footer, 8 | header, 9 | main { 10 | display: block; 11 | } 12 | 13 | blockquote, 14 | body, 15 | figure, 16 | h1, 17 | h2, 18 | h3, 19 | h4, 20 | img, 21 | p, 22 | pre { 23 | margin: 0; 24 | padding: 0; 25 | } 26 | 27 | :root, 28 | body { 29 | min-height: 100%; 30 | } 31 | 32 | img { 33 | display: inline-block; 34 | } 35 | -------------------------------------------------------------------------------- /tests/Moq.Tests.FSharpTypes/HasActionEvent.fs: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2007, Clarius Consulting, Manas Technology Solutions, InSTEDD, and Contributors. 2 | // All rights reserved. Licensed under the BSD 3-Clause License; see License.txt. 3 | 4 | namespace Moq.Tests.FSharpTypes 5 | 6 | open System; 7 | 8 | type HasActionEvent() = 9 | let event = new DelegateEvent(); 10 | 11 | [] 12 | member this.Event = event.Publish 13 | -------------------------------------------------------------------------------- /src/Moq/IMatcher.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2007, Clarius Consulting, Manas Technology Solutions, InSTEDD, and Contributors. 2 | // All rights reserved. Licensed under the BSD 3-Clause License; see License.txt. 3 | 4 | using System; 5 | 6 | namespace Moq 7 | { 8 | internal interface IMatcher 9 | { 10 | bool Matches(object argument, Type parameterType); 11 | 12 | void SetupEvaluatedSuccessfully(object argument, Type parameterType); 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /tests/Moq.Tests.FSharpTypes/HasAbstractEventHandlerEvent.fs: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2007, Clarius Consulting, Manas Technology Solutions, InSTEDD, and Contributors. 2 | // All rights reserved. Licensed under the BSD 3-Clause License; see License.txt. 3 | 4 | namespace Moq.Tests.FSharpTypes 5 | 6 | open System; 7 | 8 | [] 9 | type HasAbstractEventHandlerEvent = 10 | [] 11 | abstract member Event: IEvent 12 | -------------------------------------------------------------------------------- /src/Moq/Behaviors/NoOp.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2007, Clarius Consulting, Manas Technology Solutions, InSTEDD, and Contributors. 2 | // All rights reserved. Licensed under the BSD 3-Clause License; see License.txt. 3 | 4 | namespace Moq.Behaviors 5 | { 6 | internal sealed class NoOp : Behavior 7 | { 8 | public static readonly NoOp Instance = new NoOp(); 9 | 10 | private NoOp() 11 | { 12 | } 13 | 14 | public override void Execute(Invocation invocation) 15 | { 16 | } 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /tests/Moq.Tests.FSharpTypes/HasProperty.fs: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2007, Clarius Consulting, Manas Technology Solutions, InSTEDD, and Contributors. 2 | // All rights reserved. Licensed under the BSD 3-Clause License; see License.txt. 3 | 4 | namespace Moq.Tests.FSharpTypes 5 | 6 | open System; 7 | 8 | type HasProperty() = 9 | let mutable property = new obj() 10 | abstract Property: obj with get, set 11 | default this.Property with get() = property and set(value: obj) = property <- value 12 | -------------------------------------------------------------------------------- /tests/Moq.Tests.FSharpTypes/HasIndexer.fs: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2007, Clarius Consulting, Manas Technology Solutions, InSTEDD, and Contributors. 2 | // All rights reserved. Licensed under the BSD 3-Clause License; see License.txt. 3 | 4 | namespace Moq.Tests.FSharpTypes 5 | 6 | open System; 7 | 8 | type HasIndexer() = 9 | let mutable item = new obj() 10 | abstract Item: int -> obj with get, set 11 | default this.Item with get(index: int) = item and set (index: int) (value: obj) = item <- value 12 | -------------------------------------------------------------------------------- /src/Moq/MockExceptionReasons.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2007, Clarius Consulting, Manas Technology Solutions, InSTEDD, and Contributors. 2 | // All rights reserved. Licensed under the BSD 3-Clause License; see License.txt. 3 | 4 | using System; 5 | 6 | namespace Moq 7 | { 8 | [Flags] 9 | internal enum MockExceptionReasons 10 | { 11 | IncorrectNumberOfCalls = 1, 12 | NoMatchingCalls = 4, 13 | NoSetup = 8, 14 | ReturnValueRequired = 16, 15 | UnmatchedSetup = 32, 16 | UnverifiedInvocations = 64, 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /src/Moq/Language/Flow/IThrowsResult.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2007, Clarius Consulting, Manas Technology Solutions, InSTEDD, and Contributors. 2 | // All rights reserved. Licensed under the BSD 3-Clause License; see License.txt. 3 | 4 | using System.ComponentModel; 5 | 6 | namespace Moq.Language.Flow 7 | { 8 | /// 9 | /// Implements the fluent API. 10 | /// 11 | [EditorBrowsable(EditorBrowsableState.Never)] 12 | public interface IThrowsResult : IOccurrence, IVerifies, IFluentInterface 13 | { 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /src/Moq/Language/Flow/ICallBaseResult.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2007, Clarius Consulting, Manas Technology Solutions, InSTEDD, and Contributors. 2 | // All rights reserved. Licensed under the BSD 3-Clause License; see License.txt. 3 | 4 | using System.ComponentModel; 5 | 6 | namespace Moq.Language.Flow 7 | { 8 | /// 9 | /// Implements the fluent API. 10 | /// 11 | [EditorBrowsable(EditorBrowsableState.Never)] 12 | public interface ICallBaseResult : IThrows, IThrowsResult, IFluentInterface 13 | { 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /src/Moq/ISetupList.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2007, Clarius Consulting, Manas Technology Solutions, InSTEDD, and Contributors. 2 | // All rights reserved. Licensed under the BSD 3-Clause License; see License.txt. 3 | 4 | using System.Collections.Generic; 5 | 6 | namespace Moq 7 | { 8 | /// 9 | /// A list of setups that have been configured on a mock, 10 | /// in chronological order (that is, oldest setup first, most recent setup last). 11 | /// 12 | public interface ISetupList : IReadOnlyList 13 | { 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /Directory.Build.props: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | $(MSBuildThisFileDirectory) 5 | $(RootDirectory)build\ 6 | $(RootDirectory)out\ 7 | Release 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | -------------------------------------------------------------------------------- /src/Moq/Language/Flow/IReturnsResult.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2007, Clarius Consulting, Manas Technology Solutions, InSTEDD, and Contributors. 2 | // All rights reserved. Licensed under the BSD 3-Clause License; see License.txt. 3 | 4 | using System.ComponentModel; 5 | 6 | namespace Moq.Language.Flow 7 | { 8 | /// 9 | /// Implements the fluent API. 10 | /// 11 | [EditorBrowsable(EditorBrowsableState.Never)] 12 | public interface IReturnsResult : ICallback, IOccurrence, IRaise, IVerifies, IFluentInterface 13 | { 14 | } 15 | } -------------------------------------------------------------------------------- /tests/Moq.Tests/StringExtensions.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2007, Clarius Consulting, Manas Technology Solutions, InSTEDD, and Contributors. 2 | // All rights reserved. Licensed under the BSD 3-Clause License; see License.txt. 3 | 4 | namespace Moq.Tests 5 | { 6 | public static class StringExtensions 7 | { 8 | public static bool ContainsConsecutiveLines(this string str, params string[] lines) 9 | { 10 | var haystack = str.Replace("\r\n", "\n"); 11 | var needle = string.Join("\n", lines); 12 | return haystack.Contains(needle); 13 | } 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /src/Moq/Language/Flow/ICallbackResult.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2007, Clarius Consulting, Manas Technology Solutions, InSTEDD, and Contributors. 2 | // All rights reserved. Licensed under the BSD 3-Clause License; see License.txt. 3 | 4 | using System.ComponentModel; 5 | 6 | namespace Moq.Language.Flow 7 | { 8 | /// 9 | /// Implements the fluent API. 10 | /// 11 | [EditorBrowsable(EditorBrowsableState.Never)] 12 | public interface ICallbackResult : ICallBase, ICallBaseResult, IThrows, IThrowsResult, IFluentInterface 13 | { 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /src/Moq/Behaviors/ReturnBase.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2007, Clarius Consulting, Manas Technology Solutions, InSTEDD, and Contributors. 2 | // All rights reserved. Licensed under the BSD 3-Clause License; see License.txt. 3 | 4 | namespace Moq.Behaviors 5 | { 6 | internal sealed class ReturnBase : Behavior 7 | { 8 | public static readonly ReturnBase Instance = new ReturnBase(); 9 | 10 | private ReturnBase() 11 | { 12 | } 13 | 14 | public override void Execute(Invocation invocation) 15 | { 16 | invocation.ReturnValue = invocation.CallBase(); 17 | } 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /src/Moq/Interception/IInterceptor.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2007, Clarius Consulting, Manas Technology Solutions, InSTEDD, and Contributors. 2 | // All rights reserved. Licensed under the BSD 3-Clause License; see License.txt. 3 | 4 | namespace Moq 5 | { 6 | /// 7 | /// This role interface represents a 's ability to intercept method invocations for its . 8 | /// It is meant for use by . 9 | /// 10 | internal interface IInterceptor 11 | { 12 | void Intercept(Invocation invocation); 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /src/Moq/IInvocationList.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2007, Clarius Consulting, Manas Technology Solutions, InSTEDD, and Contributors. 2 | // All rights reserved. Licensed under the BSD 3-Clause License; see License.txt. 3 | 4 | using System.Collections.Generic; 5 | 6 | namespace Moq 7 | { 8 | /// 9 | /// A list of invocations which have been performed on a mock. 10 | /// 11 | public interface IInvocationList : IReadOnlyList 12 | { 13 | /// 14 | /// Resets all invocations recorded for this mock. 15 | /// 16 | void Clear(); 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /src/Moq/Behaviors/ReturnValue.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2007, Clarius Consulting, Manas Technology Solutions, InSTEDD, and Contributors. 2 | // All rights reserved. Licensed under the BSD 3-Clause License; see License.txt. 3 | 4 | namespace Moq.Behaviors 5 | { 6 | internal sealed class ReturnValue : Behavior 7 | { 8 | private readonly object value; 9 | 10 | public ReturnValue(object value) 11 | { 12 | this.value = value; 13 | } 14 | 15 | public object Value => this.value; 16 | 17 | public override void Execute(Invocation invocation) 18 | { 19 | invocation.ReturnValue = this.value; 20 | } 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /tests/Moq.Tests/ReflectionExtensions.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2007, Clarius Consulting, Manas Technology Solutions, InSTEDD, and Contributors. 2 | // All rights reserved. Licensed under the BSD 3-Clause License; see License.txt. 3 | 4 | using System.Collections.Generic; 5 | using System.Reflection; 6 | 7 | namespace Moq.Tests 8 | { 9 | public static class ReflectionExtensions 10 | { 11 | public static IEnumerable GetAccessors(this EventInfo @event, bool nonPublic = false) 12 | { 13 | yield return @event.GetAddMethod(nonPublic); 14 | yield return @event.GetRemoveMethod(nonPublic); 15 | } 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /src/Moq/Language/ICallBase.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2007, Clarius Consulting, Manas Technology Solutions, InSTEDD, and Contributors. 2 | // All rights reserved. Licensed under the BSD 3-Clause License; see License.txt. 3 | 4 | using System.ComponentModel; 5 | 6 | using Moq.Language.Flow; 7 | 8 | namespace Moq.Language 9 | { 10 | /// 11 | /// Defines the CallBase verb. 12 | /// 13 | [EditorBrowsable(EditorBrowsableState.Never)] 14 | public interface ICallBase : IFluentInterface 15 | { 16 | /// 17 | /// Calls the real method of the object. 18 | /// 19 | ICallBaseResult CallBase(); 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /.editorconfig: -------------------------------------------------------------------------------- 1 | ; EditorConfig to support per-solution formatting. 2 | ; Use the EditorConfig VS add-in to make this work. 3 | ; http://editorconfig.org/ 4 | 5 | ; This is the default for the codeline. 6 | root = true 7 | 8 | [*] 9 | end_of_line = CRLF 10 | 11 | [*.{cs,txt,md}] 12 | indent_style = tab 13 | indent_size = 4 14 | 15 | [*.{sln,proj,csproj,fsproj,vbproj,props,targets,xml,xdoc,config,nuspec}] 16 | indent_style = tab 17 | indent_size = 2 18 | 19 | [*.Designer.cs] 20 | indent_style = space 21 | indent_size = 4 22 | 23 | [*.resx] 24 | indent_style = space 25 | indent_size = 2 26 | 27 | [appveyor.yml] 28 | indent_style = space 29 | indent_size = 2 30 | -------------------------------------------------------------------------------- /src/Moq/Language/Flow/SetterSetupPhrase.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2007, Clarius Consulting, Manas Technology Solutions, InSTEDD, and Contributors. 2 | // All rights reserved. Licensed under the BSD 3-Clause License; see License.txt. 3 | 4 | using System; 5 | 6 | namespace Moq.Language.Flow 7 | { 8 | internal class SetterSetupPhrase : VoidSetupPhrase, ISetupSetter where T : class 9 | { 10 | public SetterSetupPhrase(MethodCall setup) : base(setup) 11 | { 12 | } 13 | 14 | public ICallbackResult Callback(Action callback) 15 | { 16 | this.Setup.SetCallbackBehavior(callback); 17 | return this; 18 | } 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /src/Moq/Condition.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2007, Clarius Consulting, Manas Technology Solutions, InSTEDD, and Contributors. 2 | // All rights reserved. Licensed under the BSD 3-Clause License; see License.txt. 3 | 4 | using System; 5 | 6 | namespace Moq 7 | { 8 | internal sealed class Condition 9 | { 10 | private Func condition; 11 | private Action success; 12 | 13 | public Condition(Func condition, Action success = null) 14 | { 15 | this.condition = condition; 16 | this.success = success; 17 | } 18 | 19 | public bool IsTrue => this.condition?.Invoke() == true; 20 | 21 | public void SetupEvaluatedSuccessfully() => this.success?.Invoke(); 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /src/Moq/Behaviors/ThrowException.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2007, Clarius Consulting, Manas Technology Solutions, InSTEDD, and Contributors. 2 | // All rights reserved. Licensed under the BSD 3-Clause License; see License.txt. 3 | 4 | using System; 5 | using System.Diagnostics; 6 | 7 | namespace Moq.Behaviors 8 | { 9 | internal sealed class ThrowException : Behavior 10 | { 11 | private readonly Exception exception; 12 | 13 | public ThrowException(Exception exception) 14 | { 15 | Debug.Assert(exception != null); 16 | 17 | this.exception = exception; 18 | } 19 | 20 | public override void Execute(Invocation invocation) 21 | { 22 | throw this.exception; 23 | } 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /src/Moq/Range.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2007, Clarius Consulting, Manas Technology Solutions, InSTEDD, and Contributors. 2 | // All rights reserved. Licensed under the BSD 3-Clause License; see License.txt. 3 | 4 | namespace Moq 5 | { 6 | /// 7 | /// Kind of range to use in a filter specified through 8 | /// . 9 | /// 10 | public enum Range 11 | { 12 | /// 13 | /// The range includes the to and 14 | /// from values. 15 | /// 16 | Inclusive, 17 | 18 | /// 19 | /// The range does not include the to and 20 | /// from values. 21 | /// 22 | Exclusive 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /docs/_includes/head.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | {{ page.title }} 6 | 7 | 8 | 9 | 10 | 11 | 12 | -------------------------------------------------------------------------------- /src/Moq/Behaviors/Callback.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2007, Clarius Consulting, Manas Technology Solutions, InSTEDD, and Contributors. 2 | // All rights reserved. Licensed under the BSD 3-Clause License; see License.txt. 3 | 4 | using System; 5 | using System.Diagnostics; 6 | 7 | namespace Moq.Behaviors 8 | { 9 | internal sealed class Callback : Behavior 10 | { 11 | private readonly Action callback; 12 | 13 | public Callback(Action callback) 14 | { 15 | Debug.Assert(callback != null); 16 | 17 | this.callback = callback; 18 | } 19 | 20 | public override void Execute(Invocation invocation) 21 | { 22 | this.callback.Invoke(invocation); 23 | } 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /tests/Moq.Tests/Async/AwaitableFixture.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2007, Clarius Consulting, Manas Technology Solutions, InSTEDD, and Contributors. 2 | // All rights reserved. Licensed under the BSD 3-Clause License; see License.txt. 3 | 4 | namespace Moq.Tests.Async 5 | { 6 | using System.Threading.Tasks; 7 | 8 | using Moq.Async; 9 | 10 | using Xunit; 11 | 12 | public class AwaitableFixture 13 | { 14 | [Fact] 15 | public void TryGetResultRecursive_is_recursive() 16 | { 17 | const int expectedResult = 42; 18 | var obj = Task.FromResult(Task.FromResult(expectedResult)); 19 | var result = Awaitable.TryGetResultRecursive(obj); 20 | Assert.Equal(expectedResult, result); 21 | } 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # stakx.Moq (abandoned) 2 | 3 | This is an abandoned fork of [Moq®](https://github.com/moq/moq), a popular and friendly mocking library for .NET. 4 | 5 | I have decided to stop work on this project since I received a copyright / trademark infringement claim by the original project owner and was forced to take down the published NuGet package. While I _could_ rename this project and re-upload it under a different name, that would perhaps not make much sense for a small, mostly unused fork with respect to its discoverability. So I consider my work on this project concluded. It was good while it lasted! 6 | 7 | [![Version](https://img.shields.io/nuget/vpre/stakx.Moq.svg)](https://www.nuget.org/packages/stakx.Moq). 8 | -------------------------------------------------------------------------------- /tests/Moq.Tests/RecordsFixture.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2007, Clarius Consulting, Manas Technology Solutions, InSTEDD, and Contributors. 2 | // All rights reserved. Licensed under the BSD 3-Clause License; see License.txt. 3 | 4 | using Xunit; 5 | 6 | namespace Moq.Tests 7 | { 8 | public class RecordsFixture 9 | { 10 | [Fact] 11 | public void Can_mock_EmptyRecord() 12 | { 13 | _ = new Mock().Object; 14 | } 15 | 16 | [Fact] 17 | public void Can_mock_DerivedEmptyRecord() 18 | { 19 | _ = new Mock().Object; 20 | } 21 | 22 | public record EmptyRecord 23 | { 24 | } 25 | 26 | public record DerivedEmptyRecord : EmptyRecord 27 | { 28 | } 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /src/Moq/Matchers/AnyMatcher.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2007, Clarius Consulting, Manas Technology Solutions, InSTEDD, and Contributors. 2 | // All rights reserved. Licensed under the BSD 3-Clause License; see License.txt. 3 | 4 | using System; 5 | using System.Diagnostics; 6 | 7 | namespace Moq.Matchers 8 | { 9 | internal sealed class AnyMatcher : IMatcher 10 | { 11 | public static AnyMatcher Instance { get; } = new AnyMatcher(); 12 | 13 | private AnyMatcher() 14 | { 15 | } 16 | 17 | public bool Matches(object argument, Type parameterType) => true; 18 | 19 | public void SetupEvaluatedSuccessfully(object argument, Type parameterType) 20 | { 21 | Debug.Assert(this.Matches(argument, parameterType)); 22 | } 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /docs/_includes/header.html: -------------------------------------------------------------------------------- 1 |
2 | 13 |
14 | -------------------------------------------------------------------------------- /src/Moq/Obsolete/MockExtensions.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2007, Clarius Consulting, Manas Technology Solutions, InSTEDD, and Contributors. 2 | // All rights reserved. Licensed under the BSD 3-Clause License; see License.txt. 3 | 4 | using System; 5 | using System.ComponentModel; 6 | 7 | namespace Moq 8 | { 9 | static partial class MockExtensions 10 | { 11 | /// 12 | /// Resets all invocations recorded for this mock. 13 | /// 14 | /// The mock whose recorded invocations should be reset. 15 | [Obsolete("Use `mock.Invocations.Clear()` instead.")] 16 | [EditorBrowsable(EditorBrowsableState.Never)] 17 | public static void ResetCalls(this Mock mock) => mock.Invocations.Clear(); 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /tests/Moq.Tests.VisualBasic/Moq.Tests.VisualBasic.vbproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | net472;netcoreapp3.1;net6.0 9 | True 10 | portable 11 | False 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | -------------------------------------------------------------------------------- /.github/workflows/sponsor.yml: -------------------------------------------------------------------------------- 1 | name: sponsor 💜 2 | on: 3 | issues: 4 | types: [opened, edited, reopened] 5 | pull_request: 6 | types: [opened, edited, synchronize, reopened] 7 | 8 | jobs: 9 | sponsor: 10 | runs-on: ubuntu-latest 11 | continue-on-error: true 12 | env: 13 | token: ${{ secrets.GH_TOKEN }} 14 | if: ${{ !endsWith(github.event.sender.login, '[bot]') && !endsWith(github.event.sender.login, 'bot') }} 15 | steps: 16 | - name: 🤘 checkout 17 | if: env.token != '' 18 | uses: actions/checkout@v2 19 | 20 | - name: 💜 sponsor 21 | if: env.token != '' 22 | uses: devlooped/actions-sponsor@main 23 | with: 24 | token: ${{ env.token }} 25 | -------------------------------------------------------------------------------- /src/Moq/MethodSetup.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2007, Clarius Consulting, Manas Technology Solutions, InSTEDD, and Contributors. 2 | // All rights reserved. Licensed under the BSD 3-Clause License; see License.txt. 3 | 4 | using System.Linq.Expressions; 5 | using System.Reflection; 6 | 7 | namespace Moq 8 | { 9 | /// 10 | /// Abstract base class for setups that target a single, specific method. 11 | /// 12 | internal abstract class MethodSetup : Setup 13 | { 14 | protected MethodSetup(Expression originalExpression, Mock mock, MethodExpectation expectation) 15 | : base(originalExpression, mock, expectation) 16 | { 17 | } 18 | 19 | public MethodInfo Method => ((MethodExpectation)this.Expectation).Method; 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /src/Moq/Interception/IProxy.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2007, Clarius Consulting, Manas Technology Solutions, InSTEDD, and Contributors. 2 | // All rights reserved. Licensed under the BSD 3-Clause License; see License.txt. 3 | 4 | using System.ComponentModel; 5 | 6 | namespace Moq.Internals 7 | { 8 | /// Do not use. (Moq requires this interface so that methods can be set up on interface mocks.) 9 | // NOTE: This type is actually specific to our DynamicProxy implementation of `ProxyFactory`. 10 | // It is directly related to `InterfaceProxy`, see the comment there. 11 | [EditorBrowsable(EditorBrowsableState.Never)] 12 | public interface IProxy 13 | { 14 | /// 15 | object Interceptor { get; } 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /src/Moq/Async/IAwaitableFactory.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2007, Clarius Consulting, Manas Technology Solutions, InSTEDD, and Contributors. 2 | // All rights reserved. Licensed under the BSD 3-Clause License; see License.txt. 3 | 4 | using System; 5 | using System.Collections.Generic; 6 | using System.Linq.Expressions; 7 | 8 | namespace Moq.Async 9 | { 10 | internal interface IAwaitableFactory 11 | { 12 | Type ResultType { get; } 13 | 14 | object CreateCompleted(object result = null); 15 | 16 | object CreateFaulted(Exception exception); 17 | 18 | object CreateFaulted(IEnumerable exceptions); 19 | 20 | Expression CreateResultExpression(Expression awaitableExpression); 21 | 22 | bool TryGetResult(object awaitable, out object result); 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /src/Moq/Behaviors/ReturnComputedValue.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2007, Clarius Consulting, Manas Technology Solutions, InSTEDD, and Contributors. 2 | // All rights reserved. Licensed under the BSD 3-Clause License; see License.txt. 3 | 4 | using System; 5 | using System.Diagnostics; 6 | 7 | namespace Moq.Behaviors 8 | { 9 | internal sealed class ReturnComputedValue : Behavior 10 | { 11 | private readonly Func valueFactory; 12 | 13 | public ReturnComputedValue(Func valueFactory) 14 | { 15 | Debug.Assert(valueFactory != null); 16 | 17 | this.valueFactory = valueFactory; 18 | } 19 | 20 | public override void Execute(Invocation invocation) 21 | { 22 | invocation.ReturnValue = this.valueFactory.Invoke(invocation); 23 | } 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /tests/Moq.Tests/HidePropertyFixture.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2007, Clarius Consulting, Manas Technology Solutions, InSTEDD, and Contributors. 2 | // All rights reserved. Licensed under the BSD 3-Clause License; see License.txt. 3 | 4 | using Xunit; 5 | 6 | namespace Moq.Tests 7 | { 8 | public class HidePropertyFixture 9 | { 10 | public class A 11 | { 12 | public string Prop { get; } 13 | } 14 | 15 | public class B : A 16 | { 17 | public new virtual int Prop { get; } 18 | } 19 | 20 | public class C : B 21 | { 22 | } 23 | 24 | [Fact] 25 | public void SetupsDerivedProperty() 26 | { 27 | var mock = new Mock(); 28 | var value = 5; 29 | 30 | mock.Setup(m => m.Prop).Returns(value); 31 | 32 | Assert.Equal(value, mock.Object.Prop); 33 | } 34 | } 35 | } 36 | -------------------------------------------------------------------------------- /src/Moq/Behaviors/ThrowComputedException.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2007, Clarius Consulting, Manas Technology Solutions, InSTEDD, and Contributors. 2 | // All rights reserved. Licensed under the BSD 3-Clause License; see License.txt. 3 | 4 | using System; 5 | using System.Diagnostics; 6 | 7 | namespace Moq.Behaviors 8 | { 9 | internal sealed class ThrowComputedException : Behavior 10 | { 11 | private readonly Func exceptionFactory; 12 | 13 | public ThrowComputedException(Func exceptionFactory) 14 | { 15 | Debug.Assert(exceptionFactory != null); 16 | 17 | this.exceptionFactory = exceptionFactory; 18 | } 19 | 20 | public override void Execute(Invocation invocation) 21 | { 22 | throw this.exceptionFactory.Invoke(invocation); 23 | } 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /src/Moq/DefaultExpressionCompiler.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2007, Clarius Consulting, Manas Technology Solutions, InSTEDD, and Contributors. 2 | // All rights reserved. Licensed under the BSD 3-Clause License; see License.txt. 3 | 4 | using System; 5 | using System.Linq.Expressions; 6 | 7 | namespace Moq 8 | { 9 | internal sealed class DefaultExpressionCompiler : ExpressionCompiler 10 | { 11 | new public static readonly DefaultExpressionCompiler Instance = new DefaultExpressionCompiler(); 12 | 13 | private DefaultExpressionCompiler() 14 | { 15 | } 16 | 17 | public override Delegate Compile(LambdaExpression expression) 18 | { 19 | return expression.Compile(); 20 | } 21 | 22 | public override TDelegate Compile(Expression expression) 23 | { 24 | return expression.Compile(); 25 | } 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /src/Moq/Interception/Mock.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2007, Clarius Consulting, Manas Technology Solutions, InSTEDD, and Contributors. 2 | // All rights reserved. Licensed under the BSD 3-Clause License; see License.txt. 3 | 4 | namespace Moq 5 | { 6 | partial class Mock : IInterceptor 7 | { 8 | void IInterceptor.Intercept(Invocation invocation) 9 | { 10 | if (HandleWellKnownMethods.Handle(invocation, this)) 11 | { 12 | return; 13 | } 14 | 15 | RecordInvocation.Handle(invocation, this); 16 | 17 | if (FindAndExecuteMatchingSetup.Handle(invocation, this)) 18 | { 19 | return; 20 | } 21 | 22 | if (HandleEventSubscription.Handle(invocation, this)) 23 | { 24 | return; 25 | } 26 | 27 | FailForStrictMock.Handle(invocation, this); 28 | 29 | Return.Handle(invocation, this); 30 | } 31 | } 32 | } 33 | -------------------------------------------------------------------------------- /src/Moq/Interception/ProxyFactory.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2007, Clarius Consulting, Manas Technology Solutions, InSTEDD, and Contributors. 2 | // All rights reserved. Licensed under the BSD 3-Clause License; see License.txt. 3 | 4 | using System; 5 | using System.Reflection; 6 | 7 | namespace Moq 8 | { 9 | internal abstract class ProxyFactory 10 | { 11 | /// 12 | /// Gets the global instance used by Moq. 13 | /// 14 | public static ProxyFactory Instance { get; } = new CastleProxyFactory(); 15 | 16 | public abstract object CreateProxy(Type mockType, IInterceptor interceptor, Type[] interfaces, object[] arguments); 17 | 18 | public abstract bool IsMethodVisible(MethodInfo method, out string messageIfNotVisible); 19 | 20 | public abstract bool IsTypeVisible(Type type); 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /src/Moq/Language/Flow/IReturnsThrows.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2007, Clarius Consulting, Manas Technology Solutions, InSTEDD, and Contributors. 2 | // All rights reserved. Licensed under the BSD 3-Clause License; see License.txt. 3 | 4 | using System.ComponentModel; 5 | 6 | namespace Moq.Language.Flow 7 | { 8 | /// 9 | /// Implements the fluent API. 10 | /// 11 | [EditorBrowsable(EditorBrowsableState.Never)] 12 | public interface IReturnsThrows : IReturns, IThrows, IFluentInterface 13 | where TMock : class 14 | { 15 | } 16 | 17 | /// 18 | /// Implements the fluent API. 19 | /// 20 | [EditorBrowsable(EditorBrowsableState.Never)] 21 | public interface IReturnsThrowsGetter : IReturnsGetter, IThrows, IFluentInterface 22 | where TMock : class 23 | { 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /src/Moq/Expressions/Visitors/Apply.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2007, Clarius Consulting, Manas Technology Solutions, InSTEDD, and Contributors. 2 | // All rights reserved. Licensed under the BSD 3-Clause License; see License.txt. 3 | 4 | using System.Linq.Expressions; 5 | 6 | namespace Moq 7 | { 8 | static partial class ExpressionExtensions 9 | { 10 | /// 11 | /// Applies the specified to this expression tree. 12 | /// 13 | /// The to which should be applied. 14 | /// The that should be applied to . 15 | public static Expression Apply(this Expression expression, ExpressionVisitor visitor) 16 | { 17 | return visitor.Visit(expression); 18 | } 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /tests/Moq.Tests/Regressions/StreamFixture.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2007, Clarius Consulting, Manas Technology Solutions, InSTEDD, and Contributors. 2 | // All rights reserved. Licensed under the BSD 3-Clause License; see License.txt. 3 | 4 | using System.IO; 5 | 6 | using Xunit; 7 | 8 | namespace Moq.Tests 9 | { 10 | public class StreamFixture 11 | { 12 | [Fact] 13 | public void ShouldMockStream() 14 | { 15 | var mockStream = new Mock(); 16 | 17 | mockStream.Setup(stream => stream.Seek(0, SeekOrigin.Begin)).Returns(0L); 18 | 19 | var position = mockStream.Object.Seek(0, SeekOrigin.Begin); 20 | 21 | Assert.Equal(0, position); 22 | 23 | mockStream.Setup(stream => stream.Flush()); 24 | mockStream.Setup(stream => stream.SetLength(100)); 25 | 26 | mockStream.Object.Flush(); 27 | mockStream.Object.SetLength(100); 28 | 29 | mockStream.VerifyAll(); 30 | } 31 | } 32 | } 33 | -------------------------------------------------------------------------------- /src/Moq/MockBehavior.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2007, Clarius Consulting, Manas Technology Solutions, InSTEDD, and Contributors. 2 | // All rights reserved. Licensed under the BSD 3-Clause License; see License.txt. 3 | 4 | namespace Moq 5 | { 6 | /// 7 | /// Options to customize the behavior of the mock. 8 | /// 9 | public enum MockBehavior 10 | { 11 | /// 12 | /// Causes the mock to always throw 13 | /// an exception for invocations that don't have a 14 | /// corresponding setup. 15 | /// 16 | Strict, 17 | /// 18 | /// Will never throw exceptions, returning default 19 | /// values when necessary (null for reference types, 20 | /// zero for value types or empty enumerables and arrays). 21 | /// 22 | Loose, 23 | /// 24 | /// Default mock behavior, which equals . 25 | /// 26 | Default = Loose, 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /src/Moq/Matchers/ExpressionMatcher.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2007, Clarius Consulting, Manas Technology Solutions, InSTEDD, and Contributors. 2 | // All rights reserved. Licensed under the BSD 3-Clause License; see License.txt. 3 | 4 | using System; 5 | using System.Diagnostics; 6 | using System.Linq.Expressions; 7 | 8 | namespace Moq.Matchers 9 | { 10 | internal class ExpressionMatcher : IMatcher 11 | { 12 | private Expression expression; 13 | 14 | public ExpressionMatcher(Expression expression) 15 | { 16 | this.expression = expression; 17 | } 18 | 19 | public bool Matches(object argument, Type parameterType) 20 | { 21 | return argument is Expression valueExpression 22 | && ExpressionComparer.Default.Equals(this.expression, valueExpression); 23 | } 24 | 25 | public void SetupEvaluatedSuccessfully(object argument, Type parameterType) 26 | { 27 | Debug.Assert(this.Matches(argument, parameterType)); 28 | } 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /src/Moq/MockExtensions.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2007, Clarius Consulting, Manas Technology Solutions, InSTEDD, and Contributors. 2 | // All rights reserved. Licensed under the BSD 3-Clause License; see License.txt. 3 | 4 | using System.ComponentModel; 5 | 6 | namespace Moq 7 | { 8 | /// 9 | /// Provides additional methods on mocks. 10 | /// 11 | [EditorBrowsable(EditorBrowsableState.Never)] 12 | public static partial class MockExtensions 13 | { 14 | /// 15 | /// Resets this mock's state. This includes its setups, configured default return values, registered event handlers, and all recorded invocations. 16 | /// 17 | /// The mock whose state should be reset. 18 | public static void Reset(this Mock mock) 19 | { 20 | mock.ConfiguredDefaultValues.Clear(); 21 | mock.MutableSetups.Clear(); 22 | mock.EventHandlers.Clear(); 23 | mock.Invocations.Clear(); 24 | } 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /src/Moq/Matchers/LazyEvalMatcher.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2007, Clarius Consulting, Manas Technology Solutions, InSTEDD, and Contributors. 2 | // All rights reserved. Licensed under the BSD 3-Clause License; see License.txt. 3 | 4 | using System; 5 | using System.Diagnostics; 6 | using System.Linq.Expressions; 7 | 8 | namespace Moq.Matchers 9 | { 10 | internal class LazyEvalMatcher : IMatcher 11 | { 12 | private Expression expression; 13 | 14 | public LazyEvalMatcher(Expression expression) 15 | { 16 | this.expression = expression; 17 | } 18 | 19 | public bool Matches(object argument, Type parameterType) 20 | { 21 | var eval = Evaluator.PartialEval(this.expression); 22 | return eval is ConstantExpression ce && new ConstantMatcher(ce.Value).Matches(argument, parameterType); 23 | } 24 | 25 | public void SetupEvaluatedSuccessfully(object argument, Type parameterType) 26 | { 27 | Debug.Assert(this.Matches(argument, parameterType)); 28 | } 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /src/Moq/IMocked.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2007, Clarius Consulting, Manas Technology Solutions, InSTEDD, and Contributors. 2 | // All rights reserved. Licensed under the BSD 3-Clause License; see License.txt. 3 | 4 | using System.ComponentModel; 5 | 6 | namespace Moq 7 | { 8 | /// 9 | /// Implemented by all generated mock object instances. 10 | /// 11 | [EditorBrowsable(EditorBrowsableState.Never)] 12 | public interface IMocked : IMocked 13 | where T : class 14 | { 15 | /// 16 | /// Reference the Mock that contains this as the mock.Object value. 17 | /// 18 | new Mock Mock { get; } 19 | } 20 | 21 | /// 22 | /// Implemented by all generated mock object instances. 23 | /// 24 | [EditorBrowsable(EditorBrowsableState.Never)] 25 | public interface IMocked 26 | { 27 | /// 28 | /// Reference the Mock that contains this as the mock.Object value. 29 | /// 30 | Mock Mock { get; } 31 | } 32 | } 33 | -------------------------------------------------------------------------------- /src/Moq/Matchers/RefMatcher.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2007, Clarius Consulting, Manas Technology Solutions, InSTEDD, and Contributors. 2 | // All rights reserved. Licensed under the BSD 3-Clause License; see License.txt. 3 | 4 | using System; 5 | using System.Diagnostics; 6 | 7 | namespace Moq.Matchers 8 | { 9 | internal class RefMatcher : IMatcher 10 | { 11 | private readonly object reference; 12 | private readonly bool referenceIsValueType; 13 | 14 | public RefMatcher(object reference) 15 | { 16 | this.reference = reference; 17 | this.referenceIsValueType = reference?.GetType().IsValueType ?? false; 18 | } 19 | 20 | public bool Matches(object argument, Type parameterType) 21 | { 22 | return this.referenceIsValueType ? object.Equals(this.reference, argument) 23 | : object.ReferenceEquals(this.reference, argument); 24 | } 25 | 26 | public void SetupEvaluatedSuccessfully(object value, Type parameterType) 27 | { 28 | Debug.Assert(this.Matches(value, parameterType)); 29 | } 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /src/Moq/Properties/AssemblyInfo.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Resources; 3 | using System.Runtime.CompilerServices; 4 | using System.Runtime.InteropServices; 5 | 6 | [assembly: ComVisible(false)] 7 | 8 | [assembly: InternalsVisibleTo("Moq.Tests, PublicKey=00240000048000009400000006020000002400005253413100040000010001009f7a95086500f8f66d892174803850fed9c22225c2ccfff21f39c8af8abfa5415b1664efd0d8e0a6f7f2513b1c11659bd84723dc7900c3d481b833a73a2bcf1ed94c16c4be64d54352c86956c89930444e9ac15124d3693e3f029818e8410f167399d6b995324b635e95353ba97bfab856abbaeb9b40c9b160070c6325e22ddc")] 9 | [assembly: InternalsVisibleTo("DynamicProxyGenAssembly2,PublicKey=0024000004800000940000000602000000240000525341310004000001000100c547cac37abd99c8db225ef2f6c8a3602f3b3606cc9891605d02baa56104f4cfc0734aa39b93bf7852f7d9266654753cc297e7d2edfe0bac1cdcf9f717241550e0a7b191195b7667bb4f64bcb8e2121380fd1d9d46ad2d92d2d15605093924cceaf74c4861eff62abf69b9291ed0a340e113be11e6a7d3113e92484cf7045cc7")] 10 | 11 | [assembly: CLSCompliant(true)] 12 | [assembly: NeutralResourcesLanguage("en-US")] 13 | -------------------------------------------------------------------------------- /src/Moq/Switches.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2007, Clarius Consulting, Manas Technology Solutions, InSTEDD, and Contributors. 2 | // All rights reserved. Licensed under the BSD 3-Clause License; see License.txt. 3 | 4 | using System; 5 | 6 | namespace Moq 7 | { 8 | /// 9 | /// Represents a switch, or a combination of switches, that can be either enabled or disabled. 10 | /// When set via or , they determine how a mock will operate. 11 | /// 12 | [Flags] 13 | public enum Switches 14 | { 15 | /// 16 | /// The default set of switches. The switches covered by this enumeration value may change between different versions of Moq. 17 | /// 18 | Default = 0, 19 | 20 | /// 21 | /// When enabled, specifies that source file information should be collected for each setup. 22 | /// This results in more helpful error messages, but may affect performance. 23 | /// 24 | CollectDiagnosticFileInfoForSetups = 1 << 0, 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /.netconfig: -------------------------------------------------------------------------------- 1 | [file ".github/workflows/includes.yml"] 2 | url = https://github.com/devlooped/oss/blob/main/.github/workflows/includes.yml 3 | sha = f08c3f28e46e28eb31e70846d65e57aa9553ce56 4 | etag = 884175b3f80b39edc1a23c6a34d58aa3c481432d4f20938f9a834dd918ef283d 5 | weak 6 | [file ".github/workflows/dotnet-file.yml"] 7 | url = https://github.com/devlooped/oss/blob/main/.github/workflows/dotnet-file.yml 8 | sha = f08c3f28e46e28eb31e70846d65e57aa9553ce56 9 | etag = 567444486383d032c1c5fbc538f07e860f92b1d08c66ac6ffb1db64ca539251c 10 | weak 11 | [file ".github/FUNDING.yml"] 12 | url = https://github.com/devlooped/.github/blob/main/.github/FUNDING.yml 13 | sha = 39f4c591716ff50dd035d2fade35e5822489ab7f 14 | etag = a944c728facd033bbdfb4ff8d0ef10d0b3a457c277dc499458df0ffc7e6409da 15 | weak 16 | [file ".github/workflows/sponsor.yml"] 17 | url = https://github.com/devlooped/oss/blob/main/.github/workflows/sponsor.yml 18 | sha = 8990ebb36199046e0b8098bad9e46dcef739c56e 19 | etag = e1dc114d2e8b57d50649989d32dbf0c9080ec77da3738a4cc79e9256d6ca5d3e 20 | weak 21 | -------------------------------------------------------------------------------- /src/Moq/MatchExpression.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2007, Clarius Consulting, Manas Technology Solutions, InSTEDD, and Contributors. 2 | // All rights reserved. Licensed under the BSD 3-Clause License; see License.txt. 3 | 4 | using System; 5 | using System.Linq.Expressions; 6 | 7 | namespace Moq 8 | { 9 | internal sealed class MatchExpression : Expression 10 | { 11 | public readonly Match Match; 12 | 13 | public MatchExpression(Match match) 14 | { 15 | this.Match = match; 16 | } 17 | 18 | public override ExpressionType NodeType => ExpressionType.Extension; 19 | 20 | public override Type Type => this.Match.RenderExpression.Type; 21 | 22 | // This node type is irreducible in order to prevent compilation. 23 | // The best possible reduction would involve `RenderExpression`, 24 | // which isn't intended to be used for that purpose. 25 | public override bool CanReduce => false; 26 | 27 | protected override Expression VisitChildren(ExpressionVisitor visitor) => this; 28 | 29 | public override string ToString() => this.Match.RenderExpression.ToString(); 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /src/Moq/ITypeMatcher.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2007, Clarius Consulting, Manas Technology Solutions, InSTEDD, and Contributors. 2 | // All rights reserved. Licensed under the BSD 3-Clause License; see License.txt. 3 | 4 | using System; 5 | 6 | namespace Moq 7 | { 8 | /// 9 | /// Types that implement this interface represent a criterion against which generic type arguments are matched. 10 | /// 11 | /// To be used in combination with . 12 | /// 13 | /// 14 | public interface ITypeMatcher 15 | { 16 | /// 17 | /// Matches the provided type argument against the criterion represented by this type matcher. 18 | /// 19 | /// 20 | /// The generic type argument that should be matched. 21 | /// 22 | /// 23 | /// if the provided type argument matched the criterion represented by this instance; 24 | /// otherwise, . 25 | /// 26 | bool Matches(Type typeArgument); 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /src/Moq/Async/Awaitable.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2007, Clarius Consulting, Manas Technology Solutions, InSTEDD, and Contributors. 2 | // All rights reserved. Licensed under the BSD 3-Clause License; see License.txt. 3 | 4 | namespace Moq.Async 5 | { 6 | internal static class Awaitable 7 | { 8 | /// 9 | /// Recursively gets the result of (i.e. "unwraps") completed awaitables 10 | /// until a value is found that isn't a successfully completed awaitable. 11 | /// 12 | /// 13 | /// As an example, given := Task.FromResult(Task.FromResult(42)), 14 | /// this method will return 42. 15 | /// 16 | /// The (possibly awaitable) object to be "unwrapped". 17 | public static object TryGetResultRecursive(object obj) 18 | { 19 | if (obj != null 20 | && AwaitableFactory.TryGet(obj.GetType()) is { } awaitableFactory 21 | && awaitableFactory.TryGetResult(obj, out var result)) 22 | { 23 | return Awaitable.TryGetResultRecursive(result); 24 | } 25 | 26 | return obj; 27 | } 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /src/Moq/Pair.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2007, Clarius Consulting, Manas Technology Solutions, InSTEDD, and Contributors. 2 | // All rights reserved. Licensed under the BSD 3-Clause License; see License.txt. 3 | 4 | using System; 5 | 6 | namespace Moq 7 | { 8 | internal readonly struct Pair : IEquatable> 9 | { 10 | public readonly T1 Item1; 11 | public readonly T2 Item2; 12 | 13 | public Pair(T1 item1, T2 item2) 14 | { 15 | this.Item1 = item1; 16 | this.Item2 = item2; 17 | } 18 | 19 | public void Deconstruct(out T1 item1, out T2 item2) 20 | { 21 | item1 = this.Item1; 22 | item2 = this.Item2; 23 | } 24 | 25 | public bool Equals(Pair other) 26 | { 27 | return object.Equals(this.Item1, other.Item1) 28 | && object.Equals(this.Item2, other.Item2); 29 | } 30 | 31 | public override bool Equals(object obj) 32 | { 33 | return obj is Pair other && this.Equals(other); 34 | } 35 | 36 | public override int GetHashCode() 37 | { 38 | return unchecked(1001 * this.Item1?.GetHashCode() ?? 101 + this.Item2?.GetHashCode() ?? 11); 39 | } 40 | } 41 | } 42 | -------------------------------------------------------------------------------- /src/Moq/Async/ValueTaskFactory.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2007, Clarius Consulting, Manas Technology Solutions, InSTEDD, and Contributors. 2 | // All rights reserved. Licensed under the BSD 3-Clause License; see License.txt. 3 | 4 | using System; 5 | using System.Collections.Generic; 6 | using System.Threading.Tasks; 7 | 8 | namespace Moq.Async 9 | { 10 | internal sealed class ValueTaskFactory : AwaitableFactory 11 | { 12 | public static readonly ValueTaskFactory Instance = new ValueTaskFactory(); 13 | 14 | private ValueTaskFactory() 15 | { 16 | } 17 | 18 | public override ValueTask CreateCompleted() 19 | { 20 | return default; 21 | } 22 | 23 | public override ValueTask CreateFaulted(Exception exception) 24 | { 25 | var tcs = new TaskCompletionSource(); 26 | tcs.SetException(exception); 27 | return new ValueTask(tcs.Task); 28 | } 29 | 30 | public override ValueTask CreateFaulted(IEnumerable exceptions) 31 | { 32 | var tcs = new TaskCompletionSource(); 33 | tcs.SetException(exceptions); 34 | return new ValueTask(tcs.Task); 35 | } 36 | } 37 | } 38 | -------------------------------------------------------------------------------- /src/Moq/ParameterTypes.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2007, Clarius Consulting, Manas Technology Solutions, InSTEDD, and Contributors. 2 | // All rights reserved. Licensed under the BSD 3-Clause License; see License.txt. 3 | 4 | using System; 5 | using System.Collections; 6 | using System.Collections.Generic; 7 | using System.Reflection; 8 | 9 | namespace Moq 10 | { 11 | /// 12 | /// Allocation-free adapter type for treating a `ParameterInfo[]` array like a `Type[]` array. 13 | /// 14 | internal readonly struct ParameterTypes : IReadOnlyList 15 | { 16 | private readonly ParameterInfo[] parameters; 17 | 18 | public ParameterTypes(ParameterInfo[] parameters) 19 | { 20 | this.parameters = parameters; 21 | } 22 | 23 | public Type this[int index] => this.parameters[index].ParameterType; 24 | 25 | public int Count => this.parameters.Length; 26 | 27 | public IEnumerator GetEnumerator() 28 | { 29 | for (int i = 0, n = this.Count; i < n; ++i) 30 | { 31 | yield return this[i]; 32 | } 33 | } 34 | 35 | IEnumerator IEnumerable.GetEnumerator() => this.GetEnumerator(); 36 | } 37 | } 38 | -------------------------------------------------------------------------------- /src/Moq/Async/TaskFactory.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2007, Clarius Consulting, Manas Technology Solutions, InSTEDD, and Contributors. 2 | // All rights reserved. Licensed under the BSD 3-Clause License; see License.txt. 3 | 4 | using System; 5 | using System.Collections.Generic; 6 | using System.Linq.Expressions; 7 | using System.Reflection; 8 | using System.Threading.Tasks; 9 | 10 | namespace Moq.Async 11 | { 12 | internal sealed class TaskFactory : AwaitableFactory 13 | { 14 | public static readonly TaskFactory Instance = new TaskFactory(); 15 | 16 | private TaskFactory() 17 | { 18 | } 19 | 20 | public override Task CreateCompleted() 21 | { 22 | return Task.FromResult(default); 23 | } 24 | 25 | public override Task CreateFaulted(Exception exception) 26 | { 27 | var tcs = new TaskCompletionSource(); 28 | tcs.SetException(exception); 29 | return tcs.Task; 30 | } 31 | 32 | public override Task CreateFaulted(IEnumerable exceptions) 33 | { 34 | var tcs = new TaskCompletionSource(); 35 | tcs.SetException(exceptions); 36 | return tcs.Task; 37 | } 38 | } 39 | } 40 | -------------------------------------------------------------------------------- /src/Moq/Language/GenericTypeParameters.tt: -------------------------------------------------------------------------------- 1 | <#+ 2 | private const int GenericTypeMax = 16; 3 | private const int GenericTypeMin = 5; 4 | 5 | private const string GenericTypeFormat = "T{0}"; 6 | private const string GenericArgumentFormat = "T{0} arg{0}"; 7 | 8 | private static readonly string[] ordinalNumbers = new[] { "first", "second", "third", "fourth", "fifth", "sixth", "seventh", "eighth", "ninth", "tenth", "eleventh", "twelfth", "thirteenth", "fourteenth", "fifteenth", "sixteenth" }; 9 | private static readonly string[] wordNumbers = new[] { "one", "two", "three", "four", "five", "six", "seven", "eight", "nine", "ten", "eleven", "twelve", "thirteen", "fourteen", "fifteen", "sixteen" }; 10 | 11 | public static string ConvertToWord(int number) 12 | { 13 | return wordNumbers[number - 1]; 14 | } 15 | 16 | public static string ConvertToOrdinal(int number) 17 | { 18 | return ordinalNumbers[number - 1]; 19 | } 20 | 21 | private static string GetGenericList(int typeCount, string format, string separator = ", ") 22 | { 23 | return string.Join(separator, Enumerable.Range(1, typeCount).Select(n => string.Format(format, n)).ToArray()); 24 | } 25 | #> -------------------------------------------------------------------------------- /src/Moq/Protected/ProtectedExtension.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2007, Clarius Consulting, Manas Technology Solutions, InSTEDD, and Contributors. 2 | // All rights reserved. Licensed under the BSD 3-Clause License; see License.txt. 3 | 4 | using System.ComponentModel; 5 | 6 | namespace Moq.Protected 7 | { 8 | /// 9 | /// Enables the Protected() method on , 10 | /// allowing setups to be set for protected members by using their 11 | /// name as a string, rather than strong-typing them which is not possible 12 | /// due to their visibility. 13 | /// 14 | [EditorBrowsable(EditorBrowsableState.Never)] 15 | public static class ProtectedExtension 16 | { 17 | /// 18 | /// Enable protected setups for the mock. 19 | /// 20 | /// Mocked object type. Typically omitted as it can be inferred from the mock instance. 21 | /// The mock to set the protected setups on. 22 | public static IProtectedMock Protected(this Mock mock) 23 | where T : class 24 | { 25 | Guard.NotNull(mock, nameof(mock)); 26 | 27 | return new ProtectedMock(mock); 28 | } 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /src/Moq/Language/ICallbackSetter.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2007, Clarius Consulting, Manas Technology Solutions, InSTEDD, and Contributors. 2 | // All rights reserved. Licensed under the BSD 3-Clause License; see License.txt. 3 | 4 | using System; 5 | using System.ComponentModel; 6 | 7 | using Moq.Language.Flow; 8 | 9 | namespace Moq.Language 10 | { 11 | /// 12 | /// Defines the Callback verb for property setter setups. 13 | /// 14 | /// Type of the property. 15 | [EditorBrowsable(EditorBrowsableState.Never)] 16 | public interface ICallbackSetter : IFluentInterface 17 | { 18 | /// 19 | /// Specifies a callback to invoke when the property is set that receives the 20 | /// property value being set. 21 | /// 22 | /// Callback method to invoke. 23 | /// 24 | /// Invokes the given callback with the property value being set. 25 | /// 26 | /// mock.SetupSet(x => x.Suspended) 27 | /// .Callback((bool state) => Console.WriteLine(state)); 28 | /// 29 | /// 30 | ICallbackResult Callback(Action action); 31 | } 32 | } 33 | -------------------------------------------------------------------------------- /src/Moq/InvocationFunc.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2007, Clarius Consulting, Manas Technology Solutions, InSTEDD, and Contributors. 2 | // All rights reserved. Licensed under the BSD 3-Clause License; see License.txt. 3 | 4 | using System; 5 | 6 | namespace Moq 7 | { 8 | /// 9 | /// A delegate-like type for use with `setup.Returns` which instructs the `Returns` verb 10 | /// to provide the callback with the current , instead of 11 | /// with a list of arguments. 12 | /// 13 | /// This type is useful in scenarios involving generic type argument matchers (such as 14 | /// ) as allows the discovery of both 15 | /// arguments and type arguments. 16 | /// 17 | /// 18 | public readonly struct InvocationFunc 19 | { 20 | internal readonly Func Func; 21 | 22 | /// 23 | /// Initializes a new instance of the type. 24 | /// 25 | /// The delegate that should be wrapped by this instance. 26 | public InvocationFunc(Func func) 27 | { 28 | this.Func = func; 29 | } 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /appveyor.yml: -------------------------------------------------------------------------------- 1 | image: Visual Studio 2022 2 | 3 | init: 4 | - git config --global core.autocrlf input 5 | 6 | environment: 7 | MSBUILD_LOGGER: C:\Program Files\AppVeyor\BuildAgent\Appveyor.MSBuildLogger.dll 8 | SN_EXE: C:\Program Files (x86)\Microsoft SDKs\Windows\v10.0A\bin\NETFX 4.7 Tools\x64\sn.exe 9 | SNK_FILE: Moq.snk 10 | FSHARPTYPES_DLL: .\tests\Moq.Tests\bin\Release\net472\Moq.Tests.FSharpTypes.dll 11 | 12 | build_script: 13 | - dotnet restore Moq.sln # --logger:"%MSBUILD_LOGGER%" 14 | - dotnet build Moq.sln --configuration Release --no-restore # --logger:"%MSBUILD_LOGGER%" 15 | 16 | before_test: 17 | - call "%SN_EXE%" -R %FSHARPTYPES_DLL% %SNK_FILE% 18 | 19 | test_script: 20 | - dotnet test --no-build --configuration Release .\tests\Moq.Tests\Moq.Tests.csproj # --logger:"%MSBUILD_LOGGER%" 21 | 22 | after_test: 23 | - dotnet pack Moq.sln --no-build --no-restore --configuration Release --output out # --logger:"%MSBUILD_LOGGER%" 24 | 25 | deploy: 26 | - provider: NuGet 27 | api_key: 28 | secure: rPsxT+QJ8XP1tw0XuAtV6TXP9j1rhQXFEDXg66U1BAv80jdHKrgR8BQpiqZ8zLA7 29 | on: 30 | appveyor_repo_tag: true 31 | 32 | nuget: 33 | project_feed: true 34 | 35 | artifacts: 36 | - path: 'out\*.nupkg' 37 | -------------------------------------------------------------------------------- /src/Moq/InvocationAction.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2007, Clarius Consulting, Manas Technology Solutions, InSTEDD, and Contributors. 2 | // All rights reserved. Licensed under the BSD 3-Clause License; see License.txt. 3 | 4 | using System; 5 | 6 | namespace Moq 7 | { 8 | /// 9 | /// A delegate-like type for use with `setup.Callback` which instructs the `Callback` verb 10 | /// to provide the callback with the current , instead of 11 | /// with a list of arguments. 12 | /// 13 | /// This type is useful in scenarios involving generic type argument matchers (such as 14 | /// ) as allows the discovery of both 15 | /// arguments and type arguments. 16 | /// 17 | /// 18 | public readonly struct InvocationAction 19 | { 20 | internal readonly Action Action; 21 | 22 | /// 23 | /// Initializes a new instance of the type. 24 | /// 25 | /// The delegate that should be wrapped by this instance. 26 | public InvocationAction(Action action) 27 | { 28 | this.Action = action; 29 | } 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /src/Moq/ImmutablePopOnlyStack.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2007, Clarius Consulting, Manas Technology Solutions, InSTEDD, and Contributors. 2 | // All rights reserved. Licensed under the BSD 3-Clause License; see License.txt. 3 | 4 | using System.Collections.Generic; 5 | using System.Diagnostics; 6 | using System.Linq; 7 | 8 | namespace Moq 9 | { 10 | internal readonly struct ImmutablePopOnlyStack 11 | { 12 | private readonly T[] items; 13 | private readonly int index; 14 | 15 | public ImmutablePopOnlyStack(IEnumerable items) 16 | { 17 | Debug.Assert(items != null); 18 | 19 | this.items = items.ToArray(); 20 | this.index = 0; 21 | } 22 | 23 | private ImmutablePopOnlyStack(T[] items, int index) 24 | { 25 | Debug.Assert(items != null); 26 | Debug.Assert(0 <= index && index <= items.Length); 27 | 28 | this.items = items; 29 | this.index = index; 30 | } 31 | 32 | public bool Empty => this.index == this.items.Length; 33 | 34 | public T Pop(out ImmutablePopOnlyStack stackBelowTop) 35 | { 36 | Debug.Assert(this.index < this.items.Length); 37 | 38 | var top = this.items[this.index]; 39 | stackBelowTop = new ImmutablePopOnlyStack(this.items, this.index + 1); 40 | return top; 41 | } 42 | } 43 | } 44 | -------------------------------------------------------------------------------- /.github/workflows/includes.yml: -------------------------------------------------------------------------------- 1 | name: +Mᐁ includes 2 | on: 3 | workflow_dispatch: 4 | push: 5 | branches: 6 | - 'main' 7 | paths: 8 | - '**.md' 9 | - '!changelog.md' 10 | 11 | jobs: 12 | includes: 13 | runs-on: ubuntu-latest 14 | steps: 15 | - name: 🤖 defaults 16 | uses: devlooped/actions-bot@v1 17 | with: 18 | name: ${{ secrets.BOT_NAME }} 19 | email: ${{ secrets.BOT_EMAIL }} 20 | gh_token: ${{ secrets.GH_TOKEN }} 21 | github_token: ${{ secrets.GITHUB_TOKEN }} 22 | 23 | - name: 🤘 checkout 24 | uses: actions/checkout@v2 25 | with: 26 | token: ${{ env.GH_TOKEN }} 27 | 28 | - name: +Mᐁ includes 29 | uses: devlooped/actions-include@v1 30 | 31 | - name: ✍ pull request 32 | uses: peter-evans/create-pull-request@v4 33 | with: 34 | base: main 35 | branch: markdown-includes 36 | delete-branch: true 37 | labels: docs 38 | author: ${{ env.BOT_AUTHOR }} 39 | committer: ${{ env.BOT_AUTHOR }} 40 | commit-message: +Mᐁ includes 41 | title: +Mᐁ includes 42 | body: +Mᐁ includes 43 | token: ${{ env.GH_TOKEN }} 44 | -------------------------------------------------------------------------------- /src/Moq/Behaviors/VerifyInvocationCount.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2007, Clarius Consulting, Manas Technology Solutions, InSTEDD, and Contributors. 2 | // All rights reserved. Licensed under the BSD 3-Clause License; see License.txt. 3 | 4 | namespace Moq.Behaviors 5 | { 6 | internal sealed class VerifyInvocationCount : Behavior 7 | { 8 | private int count; 9 | private readonly Times times; 10 | private readonly MethodCall setup; 11 | 12 | public VerifyInvocationCount(MethodCall setup, Times times) 13 | { 14 | this.setup = setup; 15 | this.times = times; 16 | this.count = 0; 17 | } 18 | 19 | public void Reset() 20 | { 21 | this.count = 0; 22 | } 23 | 24 | public override void Execute(Invocation invocation) 25 | { 26 | ++this.count; 27 | this.VerifyUpperBound(); 28 | } 29 | 30 | public void Verify() 31 | { 32 | if (!this.times.Validate(this.count)) 33 | { 34 | throw MockException.IncorrectNumberOfCalls(this.setup, this.times, this.count); 35 | } 36 | } 37 | 38 | public void VerifyUpperBound() 39 | { 40 | var (_, maxCount) = this.times; 41 | if (this.count > maxCount) 42 | { 43 | throw MockException.IncorrectNumberOfCalls(this.setup, this.times, this.count); 44 | } 45 | } 46 | } 47 | } 48 | -------------------------------------------------------------------------------- /src/Moq/IMock.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2007, Clarius Consulting, Manas Technology Solutions, InSTEDD, and Contributors. 2 | // All rights reserved. Licensed under the BSD 3-Clause License; see License.txt. 3 | 4 | namespace Moq 5 | { 6 | /// 7 | /// Covariant interface for such that casts between IMock<Employee> to IMock<Person> 8 | /// are possible. Only covers the covariant members of . 9 | /// 10 | public interface IMock where T : class 11 | { 12 | /// 13 | /// Exposes the mocked object instance. 14 | /// 15 | T Object { get; } 16 | 17 | /// 18 | /// Behavior of the mock, according to the value set in the constructor. 19 | /// 20 | MockBehavior Behavior { get; } 21 | 22 | /// 23 | /// Whether the base member virtual implementation will be called for mocked classes if no setup is matched. 24 | /// Defaults to . 25 | /// 26 | bool CallBase { get; set; } 27 | 28 | /// 29 | /// Specifies the behavior to use when returning default values for unexpected invocations on loose mocks. 30 | /// 31 | DefaultValue DefaultValue { get; set; } 32 | } 33 | } 34 | -------------------------------------------------------------------------------- /tests/Moq.Tests/CaptureMatchFixture.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2007, Clarius Consulting, Manas Technology Solutions, InSTEDD, and Contributors. 2 | // All rights reserved. Licensed under the BSD 3-Clause License; see License.txt. 3 | 4 | using Xunit; 5 | 6 | namespace Moq.Tests 7 | { 8 | public class CaptureMatchFixture 9 | { 10 | [Fact] 11 | public void CanRunCaptureCallback() 12 | { 13 | var capturedValue = string.Empty; 14 | var captureMatch = new CaptureMatch(s => capturedValue = s); 15 | 16 | var mock = new Mock(); 17 | mock.Setup(x => x.DoSomething(Capture.With(captureMatch))); 18 | 19 | mock.Object.DoSomething("Hello!"); 20 | 21 | Assert.Equal("Hello!", capturedValue); 22 | } 23 | 24 | [Fact] 25 | public void CanRunCaptureCallbackWithPredicate() 26 | { 27 | var capturedValue = string.Empty; 28 | var captureMatch = new CaptureMatch(s => capturedValue += s, s => s.StartsWith("W")); 29 | 30 | var mock = new Mock(); 31 | mock.Setup(x => x.DoSomething(Capture.With(captureMatch))); 32 | 33 | mock.Object.DoSomething("Hello!"); 34 | mock.Object.DoSomething("World!"); 35 | 36 | Assert.Equal("World!", capturedValue); 37 | } 38 | 39 | public interface IFoo 40 | { 41 | void DoSomething(string item); 42 | } 43 | } 44 | } 45 | -------------------------------------------------------------------------------- /src/Moq/Language/ICallbackGetter.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2007, Clarius Consulting, Manas Technology Solutions, InSTEDD, and Contributors. 2 | // All rights reserved. Licensed under the BSD 3-Clause License; see License.txt. 3 | 4 | using System; 5 | using System.ComponentModel; 6 | 7 | using Moq.Language.Flow; 8 | 9 | namespace Moq.Language 10 | { 11 | /// 12 | /// Defines the Callback verb for property getter setups. 13 | /// 14 | /// 15 | /// Mocked type. 16 | /// Type of the property. 17 | [EditorBrowsable(EditorBrowsableState.Never)] 18 | public interface ICallbackGetter : IFluentInterface 19 | where TMock : class 20 | { 21 | /// 22 | /// Specifies a callback to invoke when the property is retrieved. 23 | /// 24 | /// Callback method to invoke. 25 | /// 26 | /// Invokes the given callback with the property value being set. 27 | /// 28 | /// mock.SetupGet(x => x.Suspended) 29 | /// .Callback(() => called = true) 30 | /// .Returns(true); 31 | /// 32 | /// 33 | IReturnsThrowsGetter Callback(Action action); 34 | } 35 | } 36 | -------------------------------------------------------------------------------- /src/Moq/Expectation.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2007, Clarius Consulting, Manas Technology Solutions, InSTEDD, and Contributors. 2 | // All rights reserved. Licensed under the BSD 3-Clause License; see License.txt. 3 | 4 | using System; 5 | using System.Linq.Expressions; 6 | 7 | using Moq.Async; 8 | 9 | namespace Moq 10 | { 11 | /// 12 | /// Represents a set (or the "shape") of invocations 13 | /// against which concrete s can be matched. 14 | /// 15 | internal abstract class Expectation : IEquatable 16 | { 17 | public abstract LambdaExpression Expression { get; } 18 | 19 | public virtual bool HasResultExpression(out IAwaitableFactory awaitableFactory) 20 | { 21 | awaitableFactory = null; 22 | return false; 23 | } 24 | 25 | public override bool Equals(object obj) 26 | { 27 | return obj is Expectation other && this.Equals(other); 28 | } 29 | 30 | public abstract bool Equals(Expectation other); 31 | 32 | public abstract override int GetHashCode(); 33 | 34 | public abstract bool IsMatch(Invocation invocation); 35 | 36 | public virtual void SetupEvaluatedSuccessfully(Invocation invocation) 37 | { 38 | } 39 | 40 | public override string ToString() 41 | { 42 | return this.Expression.ToStringFixed(); 43 | } 44 | } 45 | } 46 | -------------------------------------------------------------------------------- /tests/Moq.Tests/CallBaseFixture.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2007, Clarius Consulting, Manas Technology Solutions, InSTEDD, and Contributors. 2 | // All rights reserved. Licensed under the BSD 3-Clause License; see License.txt. 3 | 4 | using Xunit; 5 | 6 | namespace Moq.Tests 7 | { 8 | public class CallBaseFixture 9 | { 10 | [Fact] 11 | public void Void_method_in_base_class_not_called_when_CallBase_not_specified() 12 | { 13 | var mock = new Mock(); 14 | 15 | mock.Object.Method(); 16 | 17 | Assert.False(mock.Object.MethodInvoked); 18 | } 19 | 20 | [Fact] 21 | public void Void_method_in_base_class_called_when_CallBase_specified_on_mock() 22 | { 23 | var mock = new Mock() { CallBase = true }; 24 | 25 | mock.Object.Method(); 26 | 27 | Assert.True(mock.Object.MethodInvoked); 28 | } 29 | 30 | [Fact] 31 | public void Void_method_in_base_class_called_when_CallBase_specified_on_setup() 32 | { 33 | var mock = new Mock(); 34 | mock.Setup(m => m.Method()).CallBase(); 35 | 36 | mock.Object.Method(); 37 | 38 | Assert.True(mock.Object.MethodInvoked); 39 | } 40 | 41 | public class Base 42 | { 43 | public bool MethodInvoked { get; private set; } 44 | 45 | public virtual void Method() 46 | { 47 | this.MethodInvoked = true; 48 | } 49 | } 50 | } 51 | } 52 | -------------------------------------------------------------------------------- /tests/Moq.Tests.FSharpTypes/Moq.Tests.FSharpTypes.fsproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | net472;netcoreapp3.1;net6.0 8 | True 9 | portable 10 | False 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | 32 | 33 | 34 | 35 | -------------------------------------------------------------------------------- /src/Moq/Expressions/Visitors/EvaluateCaptures.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2007, Clarius Consulting, Manas Technology Solutions, InSTEDD, and Contributors. 2 | // All rights reserved. Licensed under the BSD 3-Clause License; see License.txt. 3 | 4 | using System.Linq.Expressions; 5 | using System.Reflection; 6 | using System.Runtime.CompilerServices; 7 | 8 | namespace Moq.Expressions.Visitors 9 | { 10 | /// 11 | /// Evaluates variables that have been closed over by a lambda function. 12 | /// 13 | internal sealed class EvaluateCaptures : ExpressionVisitor 14 | { 15 | public static readonly ExpressionVisitor Rewriter = new EvaluateCaptures(); 16 | 17 | private EvaluateCaptures() 18 | { 19 | } 20 | 21 | protected override Expression VisitMember(MemberExpression node) 22 | { 23 | if (node.Member is FieldInfo fi 24 | && node.Expression is ConstantExpression ce 25 | && node.Member.DeclaringType.IsDefined(typeof(CompilerGeneratedAttribute))) 26 | { 27 | return Expression.Constant(fi.GetValue(ce.Value), node.Type); 28 | } 29 | else 30 | { 31 | return base.VisitMember(node); 32 | } 33 | } 34 | 35 | protected override Expression VisitUnary(UnaryExpression node) 36 | { 37 | return node.NodeType == ExpressionType.Quote ? node : base.VisitUnary(node); 38 | } 39 | } 40 | } 41 | -------------------------------------------------------------------------------- /src/Moq/Obsolete/SequenceExtensions.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2007, Clarius Consulting, Manas Technology Solutions, InSTEDD, and Contributors. 2 | // All rights reserved. Licensed under the BSD 3-Clause License; see License.txt. 3 | 4 | using System; 5 | using System.ComponentModel; 6 | using System.Linq.Expressions; 7 | 8 | using Moq.Language; 9 | 10 | namespace Moq 11 | { 12 | partial class SequenceExtensions 13 | { 14 | /// 15 | /// Return a sequence of values, once per call. 16 | /// 17 | [EditorBrowsable(EditorBrowsableState.Never)] 18 | [Obsolete("Please use instance method Mock.SetupSequence instead.")] 19 | public static ISetupSequentialResult SetupSequence( 20 | this Mock mock, 21 | Expression> expression) 22 | where TMock : class 23 | { 24 | return mock.SetupSequence(expression); 25 | } 26 | 27 | /// 28 | /// Performs a sequence of actions, one per call. 29 | /// 30 | [EditorBrowsable(EditorBrowsableState.Never)] 31 | [Obsolete("Please use instance method Mock.SetupSequence instead.")] 32 | public static ISetupSequentialAction SetupSequence(this Mock mock, Expression> expression) 33 | where TMock : class 34 | { 35 | return mock.SetupSequence(expression); 36 | } 37 | } 38 | } 39 | -------------------------------------------------------------------------------- /src/Moq/Async/AwaitExpression.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2007, Clarius Consulting, Manas Technology Solutions, InSTEDD, and Contributors. 2 | // All rights reserved. Licensed under the BSD 3-Clause License; see License.txt. 3 | 4 | using System; 5 | using System.Diagnostics; 6 | using System.Linq.Expressions; 7 | 8 | namespace Moq.Async 9 | { 10 | internal sealed class AwaitExpression : Expression 11 | { 12 | private readonly IAwaitableFactory awaitableFactory; 13 | private readonly Expression operand; 14 | 15 | public AwaitExpression(Expression operand, IAwaitableFactory awaitableFactory) 16 | { 17 | Debug.Assert(awaitableFactory != null); 18 | Debug.Assert(operand != null); 19 | 20 | this.awaitableFactory = awaitableFactory; 21 | this.operand = operand; 22 | } 23 | 24 | public override bool CanReduce => false; 25 | 26 | public override ExpressionType NodeType => ExpressionType.Extension; 27 | 28 | public Expression Operand => this.operand; 29 | 30 | public override Type Type => this.awaitableFactory.ResultType; 31 | 32 | public override string ToString() 33 | { 34 | return this.awaitableFactory.ResultType == typeof(void) ? $"await {this.operand}" 35 | : $"(await {this.operand})"; 36 | } 37 | 38 | protected override Expression VisitChildren(ExpressionVisitor visitor) => this; 39 | } 40 | } 41 | -------------------------------------------------------------------------------- /src/Moq/IInvocation.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2007, Clarius Consulting, Manas Technology Solutions, InSTEDD, and Contributors. 2 | // All rights reserved. Licensed under the BSD 3-Clause License; see License.txt. 3 | 4 | using System; 5 | using System.Collections.Generic; 6 | using System.Reflection; 7 | 8 | namespace Moq 9 | { 10 | /// 11 | /// Provides information about an invocation of a mock object. 12 | /// 13 | public interface IInvocation 14 | { 15 | /// 16 | /// Gets the method of the invocation. 17 | /// 18 | MethodInfo Method { get; } 19 | 20 | /// 21 | /// Gets the arguments of the invocation. 22 | /// 23 | IReadOnlyList Arguments { get; } 24 | 25 | /// 26 | /// Gets the setup that matched this invocation (or if there was no matching setup). 27 | /// 28 | ISetup MatchingSetup { get; } 29 | 30 | /// 31 | /// Gets whether this invocation was successfully verified by any of the various `Verify` methods. 32 | /// 33 | bool IsVerified { get; } 34 | 35 | /// 36 | /// The value being returned for a non-void method if no exception was thrown. 37 | /// 38 | object ReturnValue { get; } 39 | 40 | /// 41 | /// Optional exception if the method invocation results in an exception being thrown. 42 | /// 43 | Exception Exception { get; } 44 | } 45 | } -------------------------------------------------------------------------------- /src/Moq/ExpressionReconstructor.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2007, Clarius Consulting, Manas Technology Solutions, InSTEDD, and Contributors. 2 | // All rights reserved. Licensed under the BSD 3-Clause License; see License.txt. 3 | 4 | using System; 5 | using System.Linq.Expressions; 6 | 7 | namespace Moq 8 | { 9 | /// 10 | /// A reconstructs LINQ expression trees () 11 | /// from delegates. It is the counterpart to . 12 | /// 13 | internal abstract class ExpressionReconstructor 14 | { 15 | private static ExpressionReconstructor instance = new ActionObserver(); 16 | 17 | public static ExpressionReconstructor Instance 18 | { 19 | get => instance; 20 | set => instance = value ?? throw new ArgumentNullException(nameof(value)); 21 | } 22 | 23 | protected ExpressionReconstructor() 24 | { 25 | } 26 | 27 | /// 28 | /// Reconstructs a from the given delegate. 29 | /// 30 | /// The delegate for which to reconstruct a LINQ expression tree. 31 | /// Arguments to pass to a parameterized constructor of . (Optional.) 32 | public abstract Expression> ReconstructExpression(Action action, object[] ctorArgs = null); 33 | } 34 | } 35 | -------------------------------------------------------------------------------- /src/Moq/InnerMockSetup.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2007, Clarius Consulting, Manas Technology Solutions, InSTEDD, and Contributors. 2 | // All rights reserved. Licensed under the BSD 3-Clause License; see License.txt. 3 | 4 | using System.Collections.Generic; 5 | using System.Diagnostics; 6 | using System.Linq.Expressions; 7 | 8 | using Moq.Async; 9 | 10 | namespace Moq 11 | { 12 | internal sealed class InnerMockSetup : SetupWithOutParameterSupport 13 | { 14 | private readonly object returnValue; 15 | 16 | public InnerMockSetup(Expression originalExpression, Mock mock, MethodExpectation expectation, object returnValue) 17 | : base(originalExpression, mock, expectation) 18 | { 19 | Debug.Assert(Awaitable.TryGetResultRecursive(returnValue) is IMocked); 20 | 21 | this.returnValue = returnValue; 22 | 23 | this.MarkAsVerifiable(); 24 | } 25 | 26 | public override IEnumerable InnerMocks 27 | { 28 | get 29 | { 30 | var innerMock = TryGetInnerMockFrom(this.returnValue); 31 | Debug.Assert(innerMock != null); 32 | yield return innerMock; 33 | } 34 | } 35 | 36 | protected override void ExecuteCore(Invocation invocation) 37 | { 38 | invocation.ReturnValue = this.returnValue; 39 | } 40 | 41 | protected override void ResetCore() 42 | { 43 | foreach (var innerMock in this.InnerMocks) 44 | { 45 | innerMock.MutableSetups.Reset(); 46 | } 47 | } 48 | 49 | protected override void VerifySelf() 50 | { 51 | } 52 | } 53 | } 54 | -------------------------------------------------------------------------------- /tests/Moq.Tests/IsValueTypeFixture.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2007, Clarius Consulting, Manas Technology Solutions, InSTEDD, and Contributors. 2 | // All rights reserved. Licensed under the BSD 3-Clause License; see License.txt. 3 | 4 | using System; 5 | 6 | using Xunit; 7 | 8 | namespace Moq.Tests 9 | { 10 | public class IsValueTypeFixture 11 | { 12 | [Fact] 13 | public void It_IsValueType_works_for_unconstrained_type_parameter() 14 | { 15 | var mock = new Mock(); 16 | 17 | mock.Object.Unconstrained(1); // should match 18 | mock.Object.Unconstrained(true); // should match 19 | mock.Object.Unconstrained(""); 20 | mock.Object.Unconstrained(new Exception()); 21 | mock.Object.Unconstrained(3.141f); // should match 22 | 23 | mock.Verify(m => m.Unconstrained(It.IsAny()), Times.Exactly(3)); 24 | } 25 | 26 | [Fact] 27 | public void It_IsValueType_works_for_constrained_type_parameter() 28 | { 29 | var mock = new Mock(); 30 | 31 | mock.Object.Constrained(1); // should match 32 | mock.Object.Constrained(true); // should match 33 | //mock.Object.Constrained(""); 34 | //mock.Object.Constrained(new Exception()); 35 | mock.Object.Constrained(3.141f); // should match 36 | 37 | mock.Verify(m => m.Constrained(It.IsAny()), Times.Exactly(3)); 38 | } 39 | 40 | public interface IX 41 | { 42 | void Unconstrained(T arg); 43 | void Constrained(T arg) where T : struct; 44 | } 45 | } 46 | } 47 | -------------------------------------------------------------------------------- /src/Moq/Language/Flow/ISetup.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2007, Clarius Consulting, Manas Technology Solutions, InSTEDD, and Contributors. 2 | // All rights reserved. Licensed under the BSD 3-Clause License; see License.txt. 3 | 4 | using System.ComponentModel; 5 | 6 | namespace Moq.Language.Flow 7 | { 8 | /// 9 | /// Implements the fluent API. 10 | /// 11 | [EditorBrowsable(EditorBrowsableState.Never)] 12 | public interface ISetup : ICallback, ICallbackResult, IRaise, IVerifies, IFluentInterface 13 | where TMock : class 14 | { 15 | } 16 | 17 | /// 18 | /// Implements the fluent API. 19 | /// 20 | [EditorBrowsable(EditorBrowsableState.Never)] 21 | public interface ISetup : ICallback, IReturnsThrows, IVerifies, IFluentInterface 22 | where TMock : class 23 | { 24 | } 25 | 26 | /// 27 | /// Implements the fluent API. 28 | /// 29 | [EditorBrowsable(EditorBrowsableState.Never)] 30 | public interface ISetupGetter : ICallbackGetter, IReturnsThrowsGetter, IVerifies, IFluentInterface 31 | where TMock : class 32 | { 33 | } 34 | 35 | /// 36 | /// Implements the fluent API. 37 | /// 38 | [EditorBrowsable(EditorBrowsableState.Never)] 39 | public interface ISetupSetter : ICallbackSetter, ICallbackResult, IRaise, IVerifies, IFluentInterface 40 | where TMock : class 41 | { 42 | } 43 | } -------------------------------------------------------------------------------- /tests/Moq.Tests/IsSubtypeFixture.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2007, Clarius Consulting, Manas Technology Solutions, InSTEDD, and Contributors. 2 | // All rights reserved. Licensed under the BSD 3-Clause License; see License.txt. 3 | 4 | using System; 5 | using System.Collections.Generic; 6 | using System.IO; 7 | 8 | using Xunit; 9 | 10 | namespace Moq.Tests 11 | { 12 | public class IsSubtypeFixture 13 | { 14 | [Fact] 15 | public void It_IsSubtype_works_for_base_type_relationships() 16 | { 17 | var mock = new Mock(); 18 | 19 | mock.Object.Method(); // should match 20 | mock.Object.Method(); 21 | mock.Object.Method(); // should match 22 | mock.Object.Method(); 23 | mock.Object.Method(); // should match 24 | mock.Object.Method(); 25 | mock.Object.Method(); 26 | 27 | mock.Verify(m => m.Method>(), Times.Exactly(3)); 28 | } 29 | 30 | [Fact] 31 | public void It_IsSubtype_works_for_interface_implementation_relationships() 32 | { 33 | var mock = new Mock(); 34 | 35 | mock.Object.Method(); // should match 36 | mock.Object.Method(); 37 | mock.Object.Method>(); // should match 38 | mock.Object.Method(); 39 | mock.Object.Method(); 40 | 41 | mock.Verify(m => m.Method>(), Times.Exactly(2)); 42 | } 43 | 44 | public interface IX 45 | { 46 | void Method(); 47 | } 48 | } 49 | } 50 | -------------------------------------------------------------------------------- /src/Moq/Language/IRaise.tt: -------------------------------------------------------------------------------- 1 | <#@ template debug="false" hostspecific="false" language="C#" #> 2 | <#@ output extension=".Generated.cs" #> 3 | <#@ Assembly Name="System.Core" #> 4 | <#@ Import Namespace="System.Linq" #> 5 | // Copyright (c) 2007, Clarius Consulting, Manas Technology Solutions, InSTEDD, and Contributors. 6 | // All rights reserved. Licensed under the BSD 3-Clause License; see License.txt. 7 | 8 | using System; 9 | using System.ComponentModel; 10 | 11 | namespace Moq.Language 12 | { 13 | partial interface IRaise 14 | { <# 15 | for (var typeCount = 1; typeCount <= GenericTypeMax; typeCount++) 16 | { 17 | var typeList = GetGenericList(typeCount, GenericTypeFormat); 18 | #> 19 | 20 | /// 21 | /// Specifies the event that will be raised when the setup is matched. 22 | /// 23 | /// The expression that represents an event attach or detach action. 24 | /// The function that will build the 25 | /// to pass when raising the event. 26 | <# 27 | for (var typeIndex = 1; typeIndex <= typeCount; typeIndex++) 28 | { 29 | #> 30 | /// The type of the <#= ConvertToOrdinal(typeIndex) #> argument received by the expected invocation. 31 | <# 32 | } 33 | #> 34 | /// 35 | IVerifies Raises<<#= typeList #>>(Action eventExpression, Func<<#= typeList #>, EventArgs> func); 36 | <# 37 | } 38 | #> 39 | } 40 | } 41 | <#@ Include File="GenericTypeParameters.tt" #> 42 | -------------------------------------------------------------------------------- /src/Moq/Async/TaskFactory`1.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2007, Clarius Consulting, Manas Technology Solutions, InSTEDD, and Contributors. 2 | // All rights reserved. Licensed under the BSD 3-Clause License; see License.txt. 3 | 4 | using System; 5 | using System.Collections.Generic; 6 | using System.Linq.Expressions; 7 | using System.Threading.Tasks; 8 | 9 | namespace Moq.Async 10 | { 11 | internal sealed class TaskFactory : AwaitableFactory, TResult> 12 | { 13 | public override Task CreateCompleted(TResult result) 14 | { 15 | return Task.FromResult(result); 16 | } 17 | 18 | public override Task CreateFaulted(Exception exception) 19 | { 20 | var tcs = new TaskCompletionSource(); 21 | tcs.SetException(exception); 22 | return tcs.Task; 23 | } 24 | 25 | public override Task CreateFaulted(IEnumerable exceptions) 26 | { 27 | var tcs = new TaskCompletionSource(); 28 | tcs.SetException(exceptions); 29 | return tcs.Task; 30 | } 31 | 32 | public override Expression CreateResultExpression(Expression awaitableExpression) 33 | { 34 | return Expression.MakeMemberAccess( 35 | awaitableExpression, 36 | typeof(Task).GetProperty(nameof(Task.Result))); 37 | } 38 | 39 | public override bool TryGetResult(Task task, out TResult result) 40 | { 41 | if (task.Status == TaskStatus.RanToCompletion) 42 | { 43 | result = task.Result; 44 | return true; 45 | } 46 | 47 | result = default; 48 | return false; 49 | } 50 | } 51 | } 52 | -------------------------------------------------------------------------------- /src/Moq/EventHandlerCollection.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2007, Clarius Consulting, Manas Technology Solutions, InSTEDD, and Contributors. 2 | // All rights reserved. Licensed under the BSD 3-Clause License; see License.txt. 3 | 4 | using System; 5 | using System.Collections.Generic; 6 | using System.Reflection; 7 | 8 | namespace Moq 9 | { 10 | internal sealed class EventHandlerCollection 11 | { 12 | private readonly Dictionary eventHandlers; 13 | 14 | public EventHandlerCollection() 15 | { 16 | this.eventHandlers = new Dictionary(); 17 | } 18 | 19 | public void Add(EventInfo @event, Delegate eventHandler) 20 | { 21 | lock (this.eventHandlers) 22 | { 23 | this.eventHandlers[@event] = Delegate.Combine(this.TryGet(@event), eventHandler); 24 | } 25 | } 26 | 27 | public void Clear() 28 | { 29 | lock (this.eventHandlers) 30 | { 31 | this.eventHandlers.Clear(); 32 | } 33 | } 34 | 35 | public void Remove(EventInfo @event, Delegate eventHandler) 36 | { 37 | lock (this.eventHandlers) 38 | { 39 | this.eventHandlers[@event] = Delegate.Remove(this.TryGet(@event), eventHandler); 40 | } 41 | } 42 | 43 | public bool TryGet(EventInfo @event, out Delegate handlers) 44 | { 45 | lock (this.eventHandlers) 46 | { 47 | return this.eventHandlers.TryGetValue(@event, out handlers) && handlers != null; 48 | } 49 | } 50 | 51 | private Delegate TryGet(EventInfo @event) 52 | { 53 | return this.eventHandlers.TryGetValue(@event, out var handlers) ? handlers : null; 54 | } 55 | } 56 | } 57 | -------------------------------------------------------------------------------- /src/Moq/Matchers/ConstantMatcher.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2007, Clarius Consulting, Manas Technology Solutions, InSTEDD, and Contributors. 2 | // All rights reserved. Licensed under the BSD 3-Clause License; see License.txt. 3 | 4 | using System; 5 | using System.Collections; 6 | using System.Diagnostics; 7 | using System.Linq; 8 | 9 | namespace Moq.Matchers 10 | { 11 | internal class ConstantMatcher : IMatcher 12 | { 13 | private object constantValue; 14 | 15 | public ConstantMatcher(object constantValue) 16 | { 17 | this.constantValue = constantValue; 18 | } 19 | 20 | public bool Matches(object argument, Type parameterType) 21 | { 22 | if (object.Equals(argument, constantValue)) 23 | { 24 | return true; 25 | } 26 | 27 | if (this.constantValue is IEnumerable && argument is IEnumerable enumerable && 28 | !(this.constantValue is IMocked) && !(argument is IMocked)) 29 | // the above checks on the second line are necessary to ensure we have usable 30 | // implementations of IEnumerable, which might very well not be the case for 31 | // mocked objects. 32 | { 33 | return this.MatchesEnumerable(enumerable); 34 | } 35 | 36 | return false; 37 | } 38 | 39 | public void SetupEvaluatedSuccessfully(object argument, Type parameterType) 40 | { 41 | Debug.Assert(this.Matches(argument, parameterType)); 42 | } 43 | 44 | private bool MatchesEnumerable(IEnumerable enumerable) 45 | { 46 | var constValues = (IEnumerable)constantValue; 47 | return constValues.Cast().SequenceEqual(enumerable.Cast()); 48 | } 49 | } 50 | } 51 | -------------------------------------------------------------------------------- /src/Moq/Matchers/ParamArrayMatcher.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2007, Clarius Consulting, Manas Technology Solutions, InSTEDD, and Contributors. 2 | // All rights reserved. Licensed under the BSD 3-Clause License; see License.txt. 3 | 4 | using System; 5 | using System.Diagnostics; 6 | 7 | namespace Moq.Matchers 8 | { 9 | internal class ParamArrayMatcher : IMatcher 10 | { 11 | private IMatcher[] matchers; 12 | 13 | public ParamArrayMatcher(IMatcher[] matchers) 14 | { 15 | Debug.Assert(matchers != null); 16 | 17 | this.matchers = matchers; 18 | } 19 | 20 | public bool Matches(object argument, Type parameterType) 21 | { 22 | Array values = argument as Array; 23 | if (values == null || this.matchers.Length != values.Length) 24 | { 25 | return false; 26 | } 27 | 28 | var elementType = parameterType.GetElementType(); 29 | 30 | for (int index = 0; index < values.Length; index++) 31 | { 32 | if (!this.matchers[index].Matches(values.GetValue(index), elementType)) 33 | { 34 | return false; 35 | } 36 | } 37 | 38 | return true; 39 | } 40 | 41 | public void SetupEvaluatedSuccessfully(object argument, Type parameterType) 42 | { 43 | Debug.Assert(this.Matches(argument, parameterType)); 44 | Debug.Assert(argument is Array array && array.Length == this.matchers.Length); 45 | 46 | var values = (Array)argument; 47 | var elementType = parameterType.GetElementType(); 48 | for (int i = 0, n = this.matchers.Length; i < n; ++i) 49 | { 50 | this.matchers[i].SetupEvaluatedSuccessfully(values.GetValue(i), elementType); 51 | } 52 | } 53 | } 54 | } 55 | -------------------------------------------------------------------------------- /src/Moq/CaptureMatch.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2007, Clarius Consulting, Manas Technology Solutions, InSTEDD, and Contributors. 2 | // All rights reserved. Licensed under the BSD 3-Clause License; see License.txt. 3 | 4 | using System; 5 | using System.Linq.Expressions; 6 | 7 | namespace Moq 8 | { 9 | /// 10 | /// Allows creation custom matchers that can be used on setups to capture parameter values. 11 | /// 12 | /// 13 | public class CaptureMatch : Match 14 | { 15 | private static readonly Predicate matchAllPredicate = _ => true; 16 | 17 | /// 18 | /// Initializes an instance of the capture match. 19 | /// 20 | /// An action to run on captured value 21 | public CaptureMatch(Action captureCallback) 22 | : base(matchAllPredicate, () => It.IsAny(), captureCallback) 23 | { 24 | } 25 | 26 | /// 27 | /// Initializes an instance of the capture match. 28 | /// 29 | /// An action to run on captured value 30 | /// A predicate used to filter captured parameters 31 | public CaptureMatch(Action captureCallback, Expression> predicate) 32 | : base(BuildCondition(predicate), () => It.Is(predicate), captureCallback) 33 | { 34 | } 35 | 36 | private static Predicate BuildCondition(Expression> predicateExpression) 37 | { 38 | var predicate = predicateExpression.CompileUsingExpressionCompiler(); 39 | return value => predicate.Invoke(value); 40 | } 41 | } 42 | } 43 | -------------------------------------------------------------------------------- /src/Moq/Obsolete/IOccurrence.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2007, Clarius Consulting, Manas Technology Solutions, InSTEDD, and Contributors. 2 | // All rights reserved. Licensed under the BSD 3-Clause License; see License.txt. 3 | 4 | using System; 5 | using System.ComponentModel; 6 | 7 | namespace Moq.Language 8 | { 9 | /// 10 | /// Defines occurrence members to constraint setups. 11 | /// 12 | [EditorBrowsable(EditorBrowsableState.Never)] 13 | public interface IOccurrence : IFluentInterface 14 | { 15 | /// 16 | /// The expected invocation can happen at most once. 17 | /// 18 | /// 19 | /// 20 | /// var mock = new Mock<ICommand>(); 21 | /// mock.Setup(foo => foo.Execute("ping")) 22 | /// .AtMostOnce(); 23 | /// 24 | /// 25 | [Obsolete("Use 'mock.Verify(call, Times.AtMostOnce)' or 'setup.Verifiable(Times.AtMostOnce)' instead.")] 26 | [EditorBrowsable(EditorBrowsableState.Never)] 27 | IVerifies AtMostOnce(); 28 | /// 29 | /// The expected invocation can happen at most specified number of times. 30 | /// 31 | /// The number of times to accept calls. 32 | /// 33 | /// 34 | /// var mock = new Mock<ICommand>(); 35 | /// mock.Setup(foo => foo.Execute("ping")) 36 | /// .AtMost( 5 ); 37 | /// 38 | /// 39 | [Obsolete("Use 'mock.Verify(call, Times.AtMost(callCount))' or 'setup.Verifiable(Times.AtMost(callCount))' instead.")] 40 | [EditorBrowsable(EditorBrowsableState.Never)] 41 | IVerifies AtMost(int callCount); 42 | } 43 | } 44 | -------------------------------------------------------------------------------- /src/Moq/Async/ValueTaskFactory`1.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2007, Clarius Consulting, Manas Technology Solutions, InSTEDD, and Contributors. 2 | // All rights reserved. Licensed under the BSD 3-Clause License; see License.txt. 3 | 4 | using System; 5 | using System.Collections.Generic; 6 | using System.Linq.Expressions; 7 | using System.Threading.Tasks; 8 | 9 | namespace Moq.Async 10 | { 11 | internal sealed class ValueTaskFactory : AwaitableFactory, TResult> 12 | { 13 | public override ValueTask CreateCompleted(TResult result) 14 | { 15 | return new ValueTask(result); 16 | } 17 | 18 | public override ValueTask CreateFaulted(Exception exception) 19 | { 20 | var tcs = new TaskCompletionSource(); 21 | tcs.SetException(exception); 22 | return new ValueTask(tcs.Task); 23 | } 24 | 25 | public override ValueTask CreateFaulted(IEnumerable exceptions) 26 | { 27 | var tcs = new TaskCompletionSource(); 28 | tcs.SetException(exceptions); 29 | return new ValueTask(tcs.Task); 30 | } 31 | 32 | public override Expression CreateResultExpression(Expression awaitableExpression) 33 | { 34 | return Expression.MakeMemberAccess( 35 | awaitableExpression, 36 | typeof(ValueTask).GetProperty(nameof(ValueTask.Result))); 37 | } 38 | 39 | public override bool TryGetResult(ValueTask valueTask, out TResult result) 40 | { 41 | if (valueTask.IsCompletedSuccessfully) 42 | { 43 | result = valueTask.Result; 44 | return true; 45 | } 46 | 47 | result = default; 48 | return false; 49 | } 50 | } 51 | } 52 | -------------------------------------------------------------------------------- /src/Moq/Language/ISetupSequentialResult.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2007, Clarius Consulting, Manas Technology Solutions, InSTEDD, and Contributors. 2 | // All rights reserved. Licensed under the BSD 3-Clause License; see License.txt. 3 | 4 | using System; 5 | using System.ComponentModel; 6 | 7 | namespace Moq.Language 8 | { 9 | /// 10 | /// Language for ReturnSequence 11 | /// 12 | [EditorBrowsable(EditorBrowsableState.Never)] 13 | public interface ISetupSequentialResult 14 | { 15 | // would be nice to Mixin somehow the IReturn and IThrows with 16 | // another ReturnType 17 | 18 | /// 19 | /// Returns value 20 | /// 21 | ISetupSequentialResult Returns(TResult value); 22 | 23 | /// 24 | /// Uses delegate to get return value 25 | /// 26 | /// The function that will calculate the return value. 27 | ISetupSequentialResult Returns(Func valueFunction); 28 | 29 | /// 30 | /// Throws an exception 31 | /// 32 | ISetupSequentialResult Throws(Exception exception); 33 | 34 | /// 35 | /// Throws an exception 36 | /// 37 | ISetupSequentialResult Throws() where TException : Exception, new(); 38 | 39 | /// 40 | /// Uses delegate to throws an exception 41 | /// 42 | ISetupSequentialResult Throws(Func exceptionFunction) where TException : Exception; 43 | 44 | /// 45 | /// Calls original method 46 | /// 47 | ISetupSequentialResult CallBase(); 48 | } 49 | } 50 | -------------------------------------------------------------------------------- /src/Moq/Async/AwaitableFactory.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2007, Clarius Consulting, Manas Technology Solutions, InSTEDD, and Contributors. 2 | // All rights reserved. Licensed under the BSD 3-Clause License; see License.txt. 3 | 4 | using System; 5 | using System.Collections.Generic; 6 | using System.Diagnostics; 7 | using System.Threading.Tasks; 8 | 9 | namespace Moq.Async 10 | { 11 | internal static class AwaitableFactory 12 | { 13 | private static readonly Dictionary> Providers; 14 | 15 | static AwaitableFactory() 16 | { 17 | AwaitableFactory.Providers = new Dictionary> 18 | { 19 | [typeof(Task)] = awaitableType => TaskFactory.Instance, 20 | [typeof(ValueTask)] = awaitableType => ValueTaskFactory.Instance, 21 | [typeof(Task<>)] = awaitableType => AwaitableFactory.Create(typeof(TaskFactory<>), awaitableType), 22 | [typeof(ValueTask<>)] = awaitableType => AwaitableFactory.Create(typeof(ValueTaskFactory<>), awaitableType), 23 | }; 24 | } 25 | 26 | private static IAwaitableFactory Create(Type awaitableFactoryType, Type awaitableType) 27 | { 28 | return (IAwaitableFactory)Activator.CreateInstance( 29 | awaitableFactoryType.MakeGenericType( 30 | awaitableType.GetGenericArguments())); 31 | } 32 | 33 | public static IAwaitableFactory TryGet(Type type) 34 | { 35 | Debug.Assert(type != null); 36 | 37 | var key = type.IsConstructedGenericType ? type.GetGenericTypeDefinition() : type; 38 | 39 | if (AwaitableFactory.Providers.TryGetValue(key, out var provider)) 40 | { 41 | return provider.Invoke(type); 42 | } 43 | 44 | return null; 45 | } 46 | } 47 | } 48 | -------------------------------------------------------------------------------- /src/Moq/Behaviors/RaiseEvent.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2007, Clarius Consulting, Manas Technology Solutions, InSTEDD, and Contributors. 2 | // All rights reserved. Licensed under the BSD 3-Clause License; see License.txt. 3 | 4 | using System; 5 | using System.Diagnostics; 6 | using System.Linq.Expressions; 7 | 8 | namespace Moq.Behaviors 9 | { 10 | internal sealed class RaiseEvent : Behavior 11 | { 12 | private Mock mock; 13 | private LambdaExpression expression; 14 | private Delegate eventArgsFunc; 15 | private object[] eventArgsParams; 16 | 17 | public RaiseEvent(Mock mock, LambdaExpression expression, Delegate eventArgsFunc, object[] eventArgsParams) 18 | { 19 | Debug.Assert(mock != null); 20 | Debug.Assert(expression != null); 21 | Debug.Assert(eventArgsFunc != null ^ eventArgsParams != null); 22 | 23 | this.mock = mock; 24 | this.expression = expression; 25 | this.eventArgsFunc = eventArgsFunc; 26 | this.eventArgsParams = eventArgsParams; 27 | } 28 | 29 | public override void Execute(Invocation invocation) 30 | { 31 | object[] args; 32 | 33 | if (this.eventArgsParams != null) 34 | { 35 | args = this.eventArgsParams; 36 | } 37 | else 38 | { 39 | var argsFuncType = this.eventArgsFunc.GetType(); 40 | if (argsFuncType.IsGenericType && argsFuncType.GetGenericArguments().Length == 1) 41 | { 42 | args = new object[] { this.mock.Object, this.eventArgsFunc.InvokePreserveStack() }; 43 | } 44 | else 45 | { 46 | args = new object[] { this.mock.Object, this.eventArgsFunc.InvokePreserveStack(invocation.Arguments) }; 47 | } 48 | } 49 | 50 | Mock.RaiseEvent(this.mock, this.expression, this.expression.Split(), args); 51 | } 52 | } 53 | } 54 | -------------------------------------------------------------------------------- /src/Moq/DefaultValue.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2007, Clarius Consulting, Manas Technology Solutions, InSTEDD, and Contributors. 2 | // All rights reserved. Licensed under the BSD 3-Clause License; see License.txt. 3 | 4 | using System.ComponentModel; 5 | 6 | namespace Moq 7 | { 8 | /// 9 | /// Determines the way default values are generated 10 | /// calculated for loose mocks. 11 | /// 12 | public enum DefaultValue 13 | { 14 | /// 15 | /// Default behavior, which generates empty values for 16 | /// value types (i.e. default(int)), empty array and 17 | /// enumerables, and nulls for all other reference types. 18 | /// 19 | Empty, 20 | 21 | /// 22 | /// Whenever the default value generated by 23 | /// is null, replaces this value with a mock (if the type 24 | /// can be mocked). 25 | /// 26 | /// 27 | /// For sealed classes, a null value will be generated. 28 | /// 29 | Mock, 30 | 31 | /// 32 | /// 33 | /// All default value generation strategies other than or 34 | /// are represented by this enumeration value. 35 | /// 36 | /// 37 | /// Do not set (nor ) to this value. 38 | /// If you want to set up a custom default value generation strategy, set 39 | /// or instead. 40 | /// 41 | /// 42 | /// 43 | /// 44 | [EditorBrowsable(EditorBrowsableState.Advanced)] 45 | Custom 46 | } 47 | } 48 | -------------------------------------------------------------------------------- /License.txt: -------------------------------------------------------------------------------- 1 | BSD 3-Clause License 2 | 3 | Copyright (c) 2007, Clarius Consulting, Manas Technology Solutions, InSTEDD, 4 | and Contributors. 5 | Copyright (c) 2023 stakx and contributors. 6 | All rights reserved. 7 | 8 | Redistribution and use in source and binary forms, with or without 9 | modification, are permitted provided that the following conditions are met: 10 | 11 | * Redistributions of source code must retain the above copyright notice, 12 | this list of conditions and the following disclaimer. 13 | 14 | * Redistributions in binary form must reproduce the above copyright 15 | notice, this list of conditions and the following disclaimer in the 16 | documentation and/or other materials provided with the distribution. 17 | 18 | * Neither the names of the copyright holders nor the names of its 19 | contributors may be used to endorse or promote products derived from this 20 | software without specific prior written permission. 21 | 22 | THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" 23 | AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE 24 | IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE 25 | DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE 26 | FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL 27 | DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR 28 | SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER 29 | CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, 30 | OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE 31 | OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 32 | -------------------------------------------------------------------------------- /src/Moq/SequenceSetup.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2007, Clarius Consulting, Manas Technology Solutions, InSTEDD, and Contributors. 2 | // All rights reserved. Licensed under the BSD 3-Clause License; see License.txt. 3 | 4 | using System.Collections.Concurrent; 5 | using System.Diagnostics; 6 | using System.Linq.Expressions; 7 | 8 | namespace Moq 9 | { 10 | /// 11 | /// Programmable setup used by . 12 | /// 13 | internal sealed class SequenceSetup : SetupWithOutParameterSupport 14 | { 15 | // contains the behaviors set up with the `CallBase`, `Pass`, `Returns`, and `Throws` verbs 16 | private ConcurrentQueue behaviors; 17 | 18 | public SequenceSetup(Expression originalExpression, Mock mock, MethodExpectation expectation) 19 | : base(originalExpression, mock, expectation) 20 | { 21 | this.behaviors = new ConcurrentQueue(); 22 | } 23 | 24 | public void AddBehavior(Behavior behavior) 25 | { 26 | Debug.Assert(behavior != null); 27 | 28 | this.behaviors.Enqueue(behavior); 29 | } 30 | 31 | protected override void ExecuteCore(Invocation invocation) 32 | { 33 | if (this.behaviors.TryDequeue(out var behavior)) 34 | { 35 | behavior.Execute(invocation); 36 | } 37 | else 38 | { 39 | // we get here if there are more invocations than configured behaviors. 40 | // if the setup method does not have a return value, we don't need to do anything; 41 | // if it does have a return value, we produce the default value. 42 | 43 | var returnType = invocation.Method.ReturnType; 44 | if (returnType != typeof(void)) 45 | { 46 | invocation.ReturnValue = returnType.GetDefaultValue(); 47 | } 48 | } 49 | } 50 | } 51 | } 52 | -------------------------------------------------------------------------------- /tests/Moq.Tests/UnmatchableMatchersFixture.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2007, Clarius Consulting, Manas Technology Solutions, InSTEDD, and Contributors. 2 | // All rights reserved. Licensed under the BSD 3-Clause License; see License.txt. 3 | 4 | using System; 5 | 6 | using Xunit; 7 | 8 | namespace Moq.Tests 9 | { 10 | public class UnmatchableMatchersFixture 11 | { 12 | [Fact] 13 | public void Matchers_that_are_unmatchable_due_to_implicit_conversion_operator_cause_setup_failure() 14 | { 15 | var mock = new Mock(); 16 | var ex = Assert.Throws(() => mock.Setup(x => x.UseB(It.IsAny()))); 17 | Assert.Contains("'It.IsAny()' is unmatchable", ex.Message); 18 | } 19 | 20 | [Fact] 21 | public void Matchers_with_explicit_primitive_type_cast_are_not_considered_unmatchable() 22 | { 23 | var mock = new Mock(); 24 | mock.Setup(x => x.UseLong((int)It.IsAny())); 25 | } 26 | 27 | [Fact] 28 | public void Matchers_with_implicit_primitive_type_coercions_are_not_considered_unmatchable_1() 29 | { 30 | var mock = new Mock(); 31 | mock.Setup(x => x.UseLong(It.IsAny())); 32 | } 33 | 34 | [Fact] 35 | public void Matchers_with_implicit_primitive_nullable_type_coercions_are_not_considered_unmatchable_2() 36 | { 37 | var mock = new Mock(); 38 | mock.Setup(x => x.UseNullableLong(It.IsAny())); 39 | } 40 | 41 | public interface IX 42 | { 43 | void UseB(B arg); 44 | void UseInt(int arg); 45 | void UseLong(long arg); 46 | void UseNullableLong(long? arg); 47 | } 48 | 49 | public readonly struct A 50 | { 51 | } 52 | 53 | public readonly struct B 54 | { 55 | public static implicit operator B(A a) 56 | { 57 | return new B(); 58 | } 59 | } 60 | } 61 | } 62 | -------------------------------------------------------------------------------- /tests/Moq.Tests/Matchers/AnyMatcherFixture.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2007, Clarius Consulting, Manas Technology Solutions, InSTEDD, and Contributors. 2 | // All rights reserved. Licensed under the BSD 3-Clause License; see License.txt. 3 | 4 | using System; 5 | using System.Linq.Expressions; 6 | 7 | using Xunit; 8 | 9 | namespace Moq.Tests.Matchers 10 | { 11 | public class AnyMatcherFixture 12 | { 13 | [Fact] 14 | public void MatchesNull() 15 | { 16 | var expr = ToExpression(() => It.IsAny()).Body; 17 | 18 | var (matcher, _) = MatcherFactory.CreateMatcher(expr); 19 | 20 | Assert.True(matcher.Matches(null, typeof(object))); 21 | } 22 | 23 | [Fact] 24 | public void MatchesIfAssignableType() 25 | { 26 | var expr = ToExpression(() => It.IsAny()).Body; 27 | 28 | var (matcher, _) = MatcherFactory.CreateMatcher(expr); 29 | 30 | Assert.True(matcher.Matches("foo", typeof(object))); 31 | } 32 | 33 | [Fact] 34 | public void MatchesIfAssignableInterface() 35 | { 36 | var expr = ToExpression(() => It.IsAny()).Body; 37 | 38 | var (matcher, _) = MatcherFactory.CreateMatcher(expr); 39 | 40 | Assert.True(matcher.Matches(new Disposable(), typeof(IDisposable))); 41 | } 42 | 43 | [Fact] 44 | public void DoesntMatchIfNotAssignableType() 45 | { 46 | var expr = ToExpression(() => It.IsAny()).Body; 47 | 48 | var (matcher, _) = MatcherFactory.CreateMatcher(expr); 49 | 50 | Assert.False(matcher.Matches("foo", typeof(IFormatProvider))); 51 | } 52 | 53 | private LambdaExpression ToExpression(Expression> expr) 54 | { 55 | return expr; 56 | } 57 | 58 | class Disposable : IDisposable 59 | { 60 | public void Dispose() 61 | { 62 | throw new NotImplementedException(); 63 | } 64 | } 65 | } 66 | } 67 | -------------------------------------------------------------------------------- /tests/Moq.Tests/SetupsFixture.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2007, Clarius Consulting, Manas Technology Solutions, InSTEDD, and Contributors. 2 | // All rights reserved. Licensed under the BSD 3-Clause License; see License.txt. 3 | 4 | using System; 5 | using System.Linq; 6 | using System.Linq.Expressions; 7 | 8 | using Xunit; 9 | 10 | namespace Moq.Tests 11 | { 12 | public class SetupsFixture 13 | { 14 | [Fact] 15 | public void Mock_made_with_new_operator_initially_has_no_setups() 16 | { 17 | var mock = new Mock(); 18 | Assert.Empty(mock.Setups); 19 | } 20 | 21 | [Fact] 22 | public void Setup_adds_one_setup_with_same_expression_to_Setups() 23 | { 24 | Expression> setupExpression = m => m.ToString(); 25 | 26 | var mock = new Mock(); 27 | mock.Setup(setupExpression); 28 | 29 | var setup = Assert.Single(mock.Setups); 30 | Assert.Equal(setupExpression, setup.Expression, ExpressionComparer.Default); 31 | } 32 | 33 | [Fact] 34 | public void Mock_Reset_results_in_empty_Setups() 35 | { 36 | var mock = new Mock(); 37 | mock.Setup(m => m.ToString()); 38 | Assert.NotEmpty(mock.Setups); 39 | mock.Reset(); 40 | Assert.Empty(mock.Setups); 41 | } 42 | 43 | [Fact] 44 | public void Setups_includes_conditional_setups() 45 | { 46 | var mock = new Mock(); 47 | mock.When(() => true).Setup(m => m.ToString()); 48 | 49 | var setup = Assert.Single(mock.Setups); 50 | Assert.True(setup.IsConditional); 51 | } 52 | 53 | [Fact] 54 | public void Setups_includes_overridden_setups() 55 | { 56 | var mock = new Mock(); 57 | mock.Setup(m => m.ToString()); 58 | mock.Setup(m => m.ToString()); 59 | 60 | var setups = mock.Setups.ToArray(); 61 | Assert.Equal(2, setups.Length); 62 | Assert.True(setups[0].IsOverridden); 63 | Assert.False(setups[1].IsOverridden); 64 | } 65 | } 66 | } 67 | -------------------------------------------------------------------------------- /src/Moq/MockSequence.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2007, Clarius Consulting, Manas Technology Solutions, InSTEDD, and Contributors. 2 | // All rights reserved. Licensed under the BSD 3-Clause License; see License.txt. 3 | 4 | using System.ComponentModel; 5 | 6 | using Moq.Language; 7 | using Moq.Language.Flow; 8 | 9 | namespace Moq 10 | { 11 | /// 12 | /// Helper class to setup a full trace between many mocks 13 | /// 14 | public class MockSequence 15 | { 16 | int sequenceStep; 17 | int sequenceLength; 18 | 19 | /// 20 | /// Initialize a trace setup 21 | /// 22 | public MockSequence() 23 | { 24 | sequenceLength = 0; 25 | sequenceStep = 0; 26 | } 27 | 28 | /// 29 | /// Allow sequence to be repeated 30 | /// 31 | public bool Cyclic { get; set; } 32 | 33 | private void NextStep() 34 | { 35 | sequenceStep++; 36 | if (Cyclic) 37 | sequenceStep = sequenceStep % sequenceLength; 38 | } 39 | 40 | internal ISetupConditionResult For(Mock mock) 41 | where TMock : class 42 | { 43 | var expectationPosition = sequenceLength++; 44 | 45 | return new WhenPhrase(mock, new Condition( 46 | condition: () => expectationPosition == sequenceStep, 47 | success: NextStep)); 48 | } 49 | } 50 | 51 | /// 52 | /// Contains extension methods that are related to . 53 | /// 54 | [EditorBrowsable(EditorBrowsableState.Never)] 55 | public static class MockSequenceHelper 56 | { 57 | /// 58 | /// Perform an expectation in the trace. 59 | /// 60 | public static ISetupConditionResult InSequence( 61 | this Mock mock, 62 | MockSequence sequence) 63 | where TMock : class 64 | { 65 | Guard.NotNull(sequence, nameof(sequence)); 66 | 67 | return sequence.For(mock); 68 | } 69 | } 70 | } 71 | -------------------------------------------------------------------------------- /tests/Moq.Tests.ComTypes/ComTypes.idl: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2007, Clarius Consulting, Manas Technology Solutions, InSTEDD, and Contributors. 2 | // All rights reserved. Licensed under the BSD 3-Clause License; see License.txt. 3 | 4 | // See the `README.md` in the same directory as this file for instructions on 5 | // how to build `Moq.Tests.ComTypes` from these IDL definitions. 6 | 7 | // The below IDL definitions are based on information on Microsoft Docs, found 8 | // under .NET Framework 4 -> .NET Framework Advanced Development -> Interoperability 9 | // -> Advanced COM Interoperability -> Type Library to Assembly Conversion Summary 10 | // -> Imported Member Conversion: 11 | // https://docs.microsoft.com/en-us/previous-versions/dotnet/netframework-4.0/k639e386(v%3dvs.100) 12 | 13 | [uuid("2d5e9d51-b50d-4bb3-a2fd-193681186ab7")] 14 | library ComTypes 15 | { 16 | importlib("stdole32.tlb"); 17 | 18 | [uuid("26049007-4f94-41ef-94f0-efc7b15d41c5")] 19 | interface IButton : IUnknown 20 | { 21 | } 22 | 23 | [uuid("c223276a-752b-4f16-bdfc-094bc453559f")] 24 | interface IButtonEvents : IUnknown 25 | { 26 | HRESULT Click(); 27 | } 28 | 29 | [uuid("aa7236e7-e655-497d-a700-79a17efcd734")] 30 | coclass Button 31 | { 32 | [default] interface IButton; 33 | [default, source] interface IButtonEvents; 34 | } 35 | 36 | [uuid("5ee16909-c4c7-49dc-8808-219078e5d3ba")] 37 | interface IHasIndexer : IUnknown 38 | { 39 | [propget, bindable, defaultbind] HRESULT Item([in] long index, [out, retval] long *value); 40 | [propput, bindable, defaultbind] HRESULT Item([in] long index, [in] long value); 41 | } 42 | 43 | [uuid("62a88a92-d8e5-45f7-bb7f-668a74c58749")] 44 | interface IHasProperty : IUnknown 45 | { 46 | [propget] HRESULT Property([out, retval] long *value); 47 | [propput] HRESULT Property([in] long value); 48 | } 49 | } 50 | -------------------------------------------------------------------------------- /docs/Gemfile.lock: -------------------------------------------------------------------------------- 1 | GEM 2 | remote: https://rubygems.org/ 3 | specs: 4 | addressable (2.8.0) 5 | public_suffix (>= 2.0.2, < 5.0) 6 | colorator (1.1.0) 7 | concurrent-ruby (1.1.9) 8 | em-websocket (0.5.2) 9 | eventmachine (>= 0.12.9) 10 | http_parser.rb (~> 0.6.0) 11 | eventmachine (1.2.7) 12 | ffi (1.15.3) 13 | forwardable-extended (2.6.0) 14 | http_parser.rb (0.6.0) 15 | i18n (1.8.10) 16 | concurrent-ruby (~> 1.0) 17 | jekyll (4.2.0) 18 | addressable (~> 2.4) 19 | colorator (~> 1.0) 20 | em-websocket (~> 0.5) 21 | i18n (~> 1.0) 22 | jekyll-sass-converter (~> 2.0) 23 | jekyll-watch (~> 2.0) 24 | kramdown (~> 2.3) 25 | kramdown-parser-gfm (~> 1.0) 26 | liquid (~> 4.0) 27 | mercenary (~> 0.4.0) 28 | pathutil (~> 0.9) 29 | rouge (~> 3.0) 30 | safe_yaml (~> 1.0) 31 | terminal-table (~> 2.0) 32 | jekyll-relative-links (0.6.1) 33 | jekyll (>= 3.3, < 5.0) 34 | jekyll-sass-converter (2.1.0) 35 | sassc (> 2.0.1, < 3.0) 36 | jekyll-watch (2.2.1) 37 | listen (~> 3.0) 38 | kramdown (2.3.1) 39 | rexml 40 | kramdown-parser-gfm (1.1.0) 41 | kramdown (~> 2.0) 42 | liquid (4.0.3) 43 | listen (3.7.0) 44 | rb-fsevent (~> 0.10, >= 0.10.3) 45 | rb-inotify (~> 0.9, >= 0.9.10) 46 | mercenary (0.4.0) 47 | pathutil (0.16.2) 48 | forwardable-extended (~> 2.6) 49 | public_suffix (4.0.6) 50 | rb-fsevent (0.11.0) 51 | rb-inotify (0.10.1) 52 | ffi (~> 1.0) 53 | rexml (3.2.5) 54 | rouge (3.26.0) 55 | safe_yaml (1.0.5) 56 | sassc (2.4.0) 57 | ffi (~> 1.9) 58 | terminal-table (2.0.0) 59 | unicode-display_width (~> 1.1, >= 1.1.1) 60 | unicode-display_width (1.7.0) 61 | 62 | PLATFORMS 63 | x86_64-linux-musl 64 | 65 | DEPENDENCIES 66 | jekyll-relative-links 67 | 68 | BUNDLED WITH 69 | 2.2.2 70 | -------------------------------------------------------------------------------- /src/Moq/Async/AwaitableFactory`1.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2007, Clarius Consulting, Manas Technology Solutions, InSTEDD, and Contributors. 2 | // All rights reserved. Licensed under the BSD 3-Clause License; see License.txt. 3 | 4 | using System; 5 | using System.Collections.Generic; 6 | using System.Diagnostics; 7 | using System.Linq; 8 | using System.Linq.Expressions; 9 | 10 | namespace Moq.Async 11 | { 12 | /// 13 | /// Abstract base class that facilitates type-safe implementation of 14 | /// for awaitables that do not produce a result when awaited. 15 | /// 16 | internal abstract class AwaitableFactory : IAwaitableFactory 17 | { 18 | Type IAwaitableFactory.ResultType => typeof(void); 19 | 20 | public abstract TAwaitable CreateCompleted(); 21 | 22 | object IAwaitableFactory.CreateCompleted(object result) 23 | { 24 | Debug.Assert(result == null); 25 | 26 | return this.CreateCompleted(); 27 | } 28 | 29 | public abstract TAwaitable CreateFaulted(Exception exception); 30 | 31 | object IAwaitableFactory.CreateFaulted(Exception exception) 32 | { 33 | Debug.Assert(exception != null); 34 | 35 | return this.CreateFaulted(exception); 36 | } 37 | 38 | public abstract TAwaitable CreateFaulted(IEnumerable exceptions); 39 | 40 | object IAwaitableFactory.CreateFaulted(IEnumerable exceptions) 41 | { 42 | Debug.Assert(exceptions != null); 43 | Debug.Assert(exceptions.Any()); 44 | 45 | return this.CreateFaulted(exceptions); 46 | } 47 | 48 | Expression IAwaitableFactory.CreateResultExpression(Expression awaitableExpression) 49 | { 50 | return new AwaitExpression(awaitableExpression, this); 51 | } 52 | 53 | bool IAwaitableFactory.TryGetResult(object awaitable, out object result) 54 | { 55 | Debug.Assert(awaitable is TAwaitable); 56 | 57 | result = null; 58 | return false; 59 | } 60 | } 61 | } 62 | -------------------------------------------------------------------------------- /src/Moq/MockDefaultValueProvider.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2007, Clarius Consulting, Manas Technology Solutions, InSTEDD, and Contributors. 2 | // All rights reserved. Licensed under the BSD 3-Clause License; see License.txt. 3 | 4 | using System; 5 | using System.Diagnostics; 6 | 7 | namespace Moq 8 | { 9 | /// 10 | /// A that returns an empty default value 11 | /// for non-mockable types, and mocks for all other types (interfaces and 12 | /// non-sealed classes) that can be mocked. 13 | /// 14 | internal sealed class MockDefaultValueProvider : LookupOrFallbackDefaultValueProvider 15 | { 16 | internal MockDefaultValueProvider() 17 | { 18 | } 19 | 20 | internal override DefaultValue Kind => DefaultValue.Mock; 21 | 22 | protected override object GetFallbackDefaultValue(Type type, Mock mock) 23 | { 24 | Debug.Assert(type != null); 25 | Debug.Assert(type != typeof(void)); 26 | Debug.Assert(mock != null); 27 | 28 | var emptyValue = DefaultValueProvider.Empty.GetDefaultValue(type, mock); 29 | if (emptyValue != null) 30 | { 31 | return emptyValue; 32 | } 33 | else if (type.IsMockable()) 34 | { 35 | // Create a new mock to be placed to InnerMocks dictionary if it's missing there 36 | var mockType = typeof(Mock<>).MakeGenericType(type); 37 | Mock newMock = (Mock)Activator.CreateInstance(mockType, mock.Behavior); 38 | newMock.DefaultValueProvider = mock.DefaultValueProvider; 39 | if (mock.MutableSetups.FindLast(s => s is StubbedPropertiesSetup) is StubbedPropertiesSetup sts) 40 | { 41 | newMock.MutableSetups.Add(new StubbedPropertiesSetup(newMock, sts.DefaultValueProvider)); 42 | } 43 | if(!type.IsDelegateType()) 44 | { 45 | newMock.CallBase = mock.CallBase; 46 | } 47 | newMock.Switches = mock.Switches; 48 | return newMock.Object; 49 | } 50 | else 51 | { 52 | return null; 53 | } 54 | } 55 | } 56 | } 57 | -------------------------------------------------------------------------------- /tests/Moq.Tests/StringBuilderExtensionsFixture.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2007, Clarius Consulting, Manas Technology Solutions, InSTEDD, and Contributors. 2 | // All rights reserved. Licensed under the BSD 3-Clause License; see License.txt. 3 | 4 | using System; 5 | using System.Linq.Expressions; 6 | using System.Text; 7 | 8 | using Xunit; 9 | 10 | namespace Moq.Tests 11 | { 12 | public class StringBuilderExtensionsFixture 13 | { 14 | [Fact] 15 | public void AppendExpression_formats_call_to_indexer_setter_method_using_indexer_syntax() 16 | { 17 | // foo => foo.set_Item("index", "value") 18 | var foo = Expression.Parameter(typeof(IFoo), "foo"); 19 | var expression = 20 | Expression.Lambda>( 21 | Expression.Call( 22 | foo, 23 | typeof(IFoo).GetProperty("Item").SetMethod, 24 | Expression.Constant("index"), 25 | Expression.Constant("value")), 26 | foo); 27 | 28 | Assert.Equal(@"foo => foo[""index""] = ""value""", GetAppendExpressionResult(expression)); 29 | } 30 | 31 | [Fact] 32 | public void AppendExpression_formats_ternary_conditional_expression_correctly() 33 | { 34 | // 1 == 2 ? 3 : 4 35 | var expression = Expression.Condition( 36 | Expression.Equal(Expression.Constant(1), Expression.Constant(2)), 37 | Expression.Constant(3), 38 | Expression.Constant(4)); 39 | 40 | Assert.Equal(@"1 == 2 ? 3 : 4", GetAppendExpressionResult(expression)); 41 | } 42 | 43 | [Fact] 44 | public void AppendExpression_formats_is_operator_correctly() 45 | { 46 | // 1 is string 47 | var expression = Expression.TypeIs(Expression.Constant(1), typeof(string)); 48 | 49 | Assert.Equal(@"1 is string", GetAppendExpressionResult(expression)); 50 | } 51 | 52 | private string GetAppendExpressionResult(Expression expression) 53 | { 54 | return new StringBuilder().AppendExpression(expression).ToString(); 55 | } 56 | 57 | public interface IFoo 58 | { 59 | object this[object index] { get; set; } 60 | } 61 | } 62 | } 63 | -------------------------------------------------------------------------------- /tests/Moq.Tests/Matchers/ParamArrayMatcherFixture.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2007, Clarius Consulting, Manas Technology Solutions, InSTEDD, and Contributors. 2 | // All rights reserved. Licensed under the BSD 3-Clause License; see License.txt. 3 | 4 | using System; 5 | using System.Collections.Generic; 6 | using System.Linq; 7 | using System.Linq.Expressions; 8 | 9 | using Xunit; 10 | 11 | namespace Moq.Tests.Matchers 12 | { 13 | public class ParamArrayMatcherFixture 14 | { 15 | [Theory] 16 | [InlineData(42, "", true)] 17 | [InlineData(42, null, true)] 18 | [InlineData(3.141f, "", false)] 19 | [InlineData(null, "", false)] 20 | public void Matches_several_matchers_from_params_array(object first, object second, bool shouldMatch) 21 | { 22 | var seconds = new List(); 23 | var methodCallExpr = (MethodCallExpression)ToExpression(x => x.Method(It.IsAny(), Capture.In(seconds))).Body; 24 | var expr = methodCallExpr.Arguments.Single(); 25 | var parameter = typeof(IX).GetMethod("Method").GetParameters().Single(); 26 | 27 | var (matcher, _) = MatcherFactory.CreateMatcher(expr, parameter); 28 | 29 | Assert.Equal(shouldMatch, matcher.Matches(new object[] { first, second }, typeof(object[]))); 30 | } 31 | 32 | [Fact] 33 | public void SetupEvaluatedSuccessfully_succeeds_for_matching_values() 34 | { 35 | var seconds = new List(); 36 | var methodCallExpr = (MethodCallExpression)ToExpression(x => x.Method(It.IsAny(), Capture.In(seconds))).Body; 37 | var expr = methodCallExpr.Arguments.Single(); 38 | var parameter = typeof(IX).GetMethod("Method").GetParameters().Single(); 39 | 40 | var (matcher, _) = MatcherFactory.CreateMatcher(expr, parameter); 41 | 42 | matcher.SetupEvaluatedSuccessfully(new object[] { 42, "" }, typeof(object[])); 43 | } 44 | 45 | private LambdaExpression ToExpression(Expression> expr) 46 | { 47 | return expr; 48 | } 49 | 50 | public interface IX 51 | { 52 | void Method(params object[] args); 53 | } 54 | } 55 | } 56 | -------------------------------------------------------------------------------- /src/Moq/Language/ISetupConditionResult.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2007, Clarius Consulting, Manas Technology Solutions, InSTEDD, and Contributors. 2 | // All rights reserved. Licensed under the BSD 3-Clause License; see License.txt. 3 | 4 | using System; 5 | using System.ComponentModel; 6 | using System.Linq.Expressions; 7 | 8 | using Moq.Language.Flow; 9 | 10 | namespace Moq.Language 11 | { 12 | /// 13 | /// Implements the fluent API. 14 | /// 15 | [EditorBrowsable(EditorBrowsableState.Never)] 16 | public interface ISetupConditionResult where T : class 17 | { 18 | /// 19 | /// The expectation will be considered only in the former condition. 20 | /// 21 | /// 22 | /// 23 | ISetup Setup(Expression> expression); 24 | 25 | /// 26 | /// The expectation will be considered only in the former condition. 27 | /// 28 | /// 29 | /// 30 | /// 31 | ISetup Setup(Expression> expression); 32 | 33 | /// 34 | /// Setups the get. 35 | /// 36 | /// The type of the property. 37 | /// The expression. 38 | /// 39 | ISetupGetter SetupGet(Expression> expression); 40 | 41 | /// 42 | /// Setups the set. 43 | /// 44 | /// The type of the property. 45 | /// The setter expression. 46 | /// 47 | ISetupSetter SetupSet(Action setterExpression); 48 | 49 | /// 50 | /// Setups the set. 51 | /// 52 | /// The setter expression. 53 | /// 54 | ISetup SetupSet(Action setterExpression); 55 | } 56 | } 57 | -------------------------------------------------------------------------------- /src/Moq/Async/AwaitableFactory`2.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2007, Clarius Consulting, Manas Technology Solutions, InSTEDD, and Contributors. 2 | // All rights reserved. Licensed under the BSD 3-Clause License; see License.txt. 3 | 4 | using System; 5 | using System.Collections.Generic; 6 | using System.Diagnostics; 7 | using System.Linq; 8 | using System.Linq.Expressions; 9 | 10 | namespace Moq.Async 11 | { 12 | /// 13 | /// Abstract base class that facilitates type-safe implementation of 14 | /// for awaitables that produce a result when awaited. 15 | /// 16 | internal abstract class AwaitableFactory : IAwaitableFactory 17 | { 18 | public Type ResultType => typeof(TResult); 19 | 20 | public abstract TAwaitable CreateCompleted(TResult result); 21 | 22 | object IAwaitableFactory.CreateCompleted(object result) 23 | { 24 | Debug.Assert(result is TResult || result == null); 25 | 26 | return this.CreateCompleted((TResult)result); 27 | } 28 | 29 | public abstract TAwaitable CreateFaulted(Exception exception); 30 | 31 | object IAwaitableFactory.CreateFaulted(Exception exception) 32 | { 33 | Debug.Assert(exception != null); 34 | 35 | return this.CreateFaulted(exception); 36 | } 37 | 38 | public abstract TAwaitable CreateFaulted(IEnumerable exceptions); 39 | 40 | object IAwaitableFactory.CreateFaulted(IEnumerable exceptions) 41 | { 42 | Debug.Assert(exceptions != null); 43 | Debug.Assert(exceptions.Any()); 44 | 45 | return this.CreateFaulted(exceptions); 46 | } 47 | 48 | public abstract bool TryGetResult(TAwaitable awaitable, out TResult result); 49 | 50 | public abstract Expression CreateResultExpression(Expression awaitableExpression); 51 | 52 | bool IAwaitableFactory.TryGetResult(object awaitable, out object result) 53 | { 54 | Debug.Assert(awaitable is TAwaitable); 55 | 56 | if (this.TryGetResult((TAwaitable)awaitable, out var r)) 57 | { 58 | result = r; 59 | return true; 60 | } 61 | 62 | result = null; 63 | return false; 64 | } 65 | } 66 | } 67 | -------------------------------------------------------------------------------- /src/Moq/Language/Flow/WhenPhrase.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2007, Clarius Consulting, Manas Technology Solutions, InSTEDD, and Contributors. 2 | // All rights reserved. Licensed under the BSD 3-Clause License; see License.txt. 3 | 4 | using System; 5 | using System.Linq.Expressions; 6 | 7 | namespace Moq.Language.Flow 8 | { 9 | internal sealed class WhenPhrase : ISetupConditionResult 10 | where T : class 11 | { 12 | private Mock mock; 13 | private Condition condition; 14 | 15 | public WhenPhrase(Mock mock, Condition condition) 16 | { 17 | this.mock = mock; 18 | this.condition = condition; 19 | } 20 | 21 | public ISetup Setup(Expression> expression) 22 | { 23 | var setup = Mock.Setup(mock, expression, this.condition); 24 | return new VoidSetupPhrase(setup); 25 | } 26 | 27 | public ISetup Setup(Expression> expression) 28 | { 29 | var setup = Mock.Setup(mock, expression, this.condition); 30 | return new NonVoidSetupPhrase(setup); 31 | } 32 | 33 | public ISetupGetter SetupGet(Expression> expression) 34 | { 35 | var setup = Mock.SetupGet(mock, expression, this.condition); 36 | return new NonVoidSetupPhrase(setup); 37 | } 38 | 39 | public ISetupSetter SetupSet(Action setterExpression) 40 | { 41 | Guard.NotNull(setterExpression, nameof(setterExpression)); 42 | var expression = ExpressionReconstructor.Instance.ReconstructExpression(setterExpression, this.mock.ConstructorArguments); 43 | 44 | var setup = Mock.SetupSet(mock, expression, this.condition); 45 | return new SetterSetupPhrase(setup); 46 | } 47 | 48 | public ISetup SetupSet(Action setterExpression) 49 | { 50 | Guard.NotNull(setterExpression, nameof(setterExpression)); 51 | var expression = ExpressionReconstructor.Instance.ReconstructExpression(setterExpression, this.mock.ConstructorArguments); 52 | 53 | var setup = Mock.SetupSet(mock, expression, this.condition); 54 | return new VoidSetupPhrase(setup); 55 | } 56 | } 57 | } 58 | -------------------------------------------------------------------------------- /tests/Moq.Tests/InterceptorFixture.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2007, Clarius Consulting, Manas Technology Solutions, InSTEDD, and Contributors. 2 | // All rights reserved. Licensed under the BSD 3-Clause License; see License.txt. 3 | 4 | using System; 5 | 6 | using Xunit; 7 | 8 | namespace Moq.Tests 9 | { 10 | public class InterceptorFixture 11 | { 12 | /// 13 | /// These tests document which methods can be intercepted (i.e. seen) by s. 14 | /// 15 | public class Method_interceptability 16 | { 17 | [Theory] 18 | [InlineData(typeof(ClassType))] 19 | [InlineData(typeof(IInterfaceType))] 20 | public void Object_Equals(Type typeToProxy) 21 | { 22 | var proxy = CreateProxy(typeToProxy, new Echo(true)); 23 | var returnValue = proxy.Equals(42); 24 | Assert.True(returnValue); 25 | } 26 | 27 | [Theory] 28 | [InlineData(typeof(ClassType))] 29 | [InlineData(typeof(IInterfaceType))] 30 | public void Object_GetHashCode(Type typeToProxy) 31 | { 32 | var proxy = CreateProxy(typeToProxy, new Echo(42)); 33 | var returnValue = proxy.GetHashCode(); 34 | Assert.Equal(42, returnValue); 35 | } 36 | 37 | [Theory] 38 | [InlineData(typeof(ClassType))] 39 | [InlineData(typeof(IInterfaceType))] 40 | public void Object_ToString(Type typeToProxy) 41 | { 42 | var proxy = CreateProxy(typeToProxy, new Echo("42")); 43 | var returnValue = proxy.ToString(); 44 | Assert.Equal("42", returnValue); 45 | } 46 | 47 | public abstract class ClassType { } 48 | 49 | public interface IInterfaceType { } 50 | } 51 | 52 | private static object CreateProxy(Type type, IInterceptor interceptor) 53 | { 54 | return ProxyFactory.Instance.CreateProxy(type, interceptor, Type.EmptyTypes, new object[0]); 55 | } 56 | 57 | private sealed class Echo : IInterceptor 58 | { 59 | private readonly object returnValue; 60 | 61 | public Echo(object returnValue) 62 | { 63 | this.returnValue = returnValue; 64 | } 65 | 66 | public void Intercept(Invocation invocation) 67 | { 68 | invocation.ReturnValue = this.returnValue; 69 | } 70 | } 71 | } 72 | } 73 | -------------------------------------------------------------------------------- /src/Moq/SetupWithOutParameterSupport.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2007, Clarius Consulting, Manas Technology Solutions, InSTEDD, and Contributors. 2 | // All rights reserved. Licensed under the BSD 3-Clause License; see License.txt. 3 | 4 | using System; 5 | using System.Collections.Generic; 6 | using System.Diagnostics; 7 | using System.Linq.Expressions; 8 | using System.Reflection; 9 | 10 | using Moq.Properties; 11 | 12 | namespace Moq 13 | { 14 | internal abstract class SetupWithOutParameterSupport : MethodSetup 15 | { 16 | private readonly List> outValues; 17 | 18 | protected SetupWithOutParameterSupport(Expression originalExpression, Mock mock, MethodExpectation expectation) 19 | : base(originalExpression, mock, expectation) 20 | { 21 | Debug.Assert(expectation != null); 22 | 23 | this.outValues = GetOutValues(expectation.Arguments, expectation.Method.GetParameters()); 24 | } 25 | 26 | public sealed override void SetOutParameters(Invocation invocation) 27 | { 28 | if (this.outValues != null) 29 | { 30 | foreach (var item in this.outValues) 31 | { 32 | invocation.Arguments[item.Key] = item.Value; 33 | } 34 | } 35 | } 36 | 37 | private static List> GetOutValues(IReadOnlyList arguments, ParameterInfo[] parameters) 38 | { 39 | List> outValues = null; 40 | for (int i = 0, n = parameters.Length; i < n; ++i) 41 | { 42 | var parameter = parameters[i]; 43 | if (parameter.ParameterType.IsByRef) 44 | { 45 | if ((parameter.Attributes & (ParameterAttributes.In | ParameterAttributes.Out)) == ParameterAttributes.Out) 46 | { 47 | var constant = arguments[i].PartialEval() as ConstantExpression; 48 | if (constant == null) 49 | { 50 | throw new NotSupportedException(Resources.OutExpressionMustBeConstantValue); 51 | } 52 | 53 | if (outValues == null) 54 | { 55 | outValues = new List>(); 56 | } 57 | 58 | outValues.Add(new KeyValuePair(i, constant.Value)); 59 | } 60 | } 61 | } 62 | return outValues; 63 | } 64 | } 65 | } 66 | -------------------------------------------------------------------------------- /src/Moq/EmptyDefaultValueProvider.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2007, Clarius Consulting, Manas Technology Solutions, InSTEDD, and Contributors. 2 | // All rights reserved. Licensed under the BSD 3-Clause License; see License.txt. 3 | 4 | using System; 5 | using System.Collections; 6 | using System.Collections.Generic; 7 | using System.Linq; 8 | 9 | namespace Moq 10 | { 11 | /// 12 | /// A that returns an empty default value 13 | /// for invocations that do not have setups or return values, with loose mocks. 14 | /// This is the default behavior for a mock. 15 | /// 16 | internal sealed class EmptyDefaultValueProvider : LookupOrFallbackDefaultValueProvider 17 | { 18 | internal EmptyDefaultValueProvider() 19 | { 20 | base.Register(typeof(Array), CreateArray); 21 | base.Register(typeof(IEnumerable), CreateEnumerable); 22 | base.Register(typeof(IEnumerable<>), CreateEnumerableOf); 23 | base.Register(typeof(IQueryable), CreateQueryable); 24 | base.Register(typeof(IQueryable<>), CreateQueryableOf); 25 | } 26 | 27 | internal override DefaultValue Kind => DefaultValue.Empty; 28 | 29 | private static object CreateArray(Type type, Mock mock) 30 | { 31 | var elementType = type.GetElementType(); 32 | var lengths = new int[type.GetArrayRank()]; 33 | return Array.CreateInstance(elementType, lengths); 34 | } 35 | 36 | private static object CreateEnumerable(Type type, Mock mock) 37 | { 38 | return new object[0]; 39 | } 40 | 41 | private static object CreateEnumerableOf(Type type, Mock mock) 42 | { 43 | var elementType = type.GetGenericArguments()[0]; 44 | return Array.CreateInstance(elementType, 0); 45 | } 46 | 47 | private static object CreateQueryable(Type type, Mock mock) 48 | { 49 | return new object[0].AsQueryable(); 50 | } 51 | 52 | private static object CreateQueryableOf(Type type, Mock mock) 53 | { 54 | var elementType = type.GetGenericArguments()[0]; 55 | var array = Array.CreateInstance(elementType, 0); 56 | 57 | return typeof(Queryable).GetMethods("AsQueryable") 58 | .Single(x => x.IsGenericMethod) 59 | .MakeGenericMethod(elementType) 60 | .Invoke(null, new[] { array }); 61 | } 62 | } 63 | } 64 | -------------------------------------------------------------------------------- /src/Moq/Language/IRaise.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2007, Clarius Consulting, Manas Technology Solutions, InSTEDD, and Contributors. 2 | // All rights reserved. Licensed under the BSD 3-Clause License; see License.txt. 3 | 4 | using System; 5 | using System.ComponentModel; 6 | 7 | namespace Moq.Language 8 | { 9 | /// 10 | /// Defines the Raises verb. 11 | /// 12 | [EditorBrowsable(EditorBrowsableState.Never)] 13 | public partial interface IRaise : IFluentInterface 14 | { 15 | /// 16 | /// Specifies the event that will be raised 17 | /// when the setup is met. 18 | /// 19 | /// An expression that represents an event attach or detach action. 20 | /// The event arguments to pass for the raised event. 21 | /// 22 | /// The following example shows how to raise an event when 23 | /// the setup is met: 24 | /// 25 | /// var mock = new Mock<IContainer>(); 26 | /// 27 | /// mock.Setup(add => add.Add(It.IsAny<string>(), It.IsAny<object>())) 28 | /// .Raises(add => add.Added += null, EventArgs.Empty); 29 | /// 30 | /// 31 | IVerifies Raises(Action eventExpression, EventArgs args); 32 | 33 | /// 34 | /// Specifies the event that will be raised 35 | /// when the setup is matched. 36 | /// 37 | /// An expression that represents an event attach or detach action. 38 | /// A function that will build the 39 | /// to pass when raising the event. 40 | /// 41 | IVerifies Raises(Action eventExpression, Func func); 42 | 43 | /// 44 | /// Specifies the custom event that will be raised 45 | /// when the setup is matched. 46 | /// 47 | /// An expression that represents an event attach or detach action. 48 | /// The arguments to pass to the custom delegate (non EventHandler-compatible). 49 | IVerifies Raises(Action eventExpression, params object[] args); 50 | } 51 | } 52 | -------------------------------------------------------------------------------- /src/Moq/Language/IReturnsGetter.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2007, Clarius Consulting, Manas Technology Solutions, InSTEDD, and Contributors. 2 | // All rights reserved. Licensed under the BSD 3-Clause License; see License.txt. 3 | 4 | using System; 5 | using System.ComponentModel; 6 | 7 | using Moq.Language.Flow; 8 | 9 | namespace Moq.Language 10 | { 11 | /// 12 | /// Defines the Returns verb for property get setups. 13 | /// 14 | /// Mocked type. 15 | /// Type of the property. 16 | [EditorBrowsable(EditorBrowsableState.Never)] 17 | public interface IReturnsGetter : IFluentInterface 18 | where TMock : class 19 | { 20 | /// 21 | /// Specifies the value to return. 22 | /// 23 | /// The value to return, or . 24 | /// 25 | /// Return a true value from the property getter call: 26 | /// 27 | /// mock.SetupGet(x => x.Suspended) 28 | /// .Returns(true); 29 | /// 30 | /// 31 | IReturnsResult Returns(TProperty value); 32 | 33 | /// 34 | /// Specifies a function that will calculate the value to return for the property. 35 | /// 36 | /// The function that will calculate the return value. 37 | /// 38 | /// Return a calculated value when the property is retrieved: 39 | /// 40 | /// mock.SetupGet(x => x.Suspended) 41 | /// .Returns(() => returnValues[0]); 42 | /// 43 | /// The lambda expression to retrieve the return value is lazy-executed, 44 | /// meaning that its value may change depending on the moment the property 45 | /// is retrieved and the value the returnValues array has at 46 | /// that moment. 47 | /// 48 | IReturnsResult Returns(Func valueFunction); 49 | 50 | /// 51 | /// Calls the real property of the object and returns its return value. 52 | /// 53 | /// The value calculated by the real property of the object. 54 | IReturnsResult CallBase(); 55 | } 56 | } 57 | -------------------------------------------------------------------------------- /src/Moq/Language/IReturns.tt: -------------------------------------------------------------------------------- 1 | <#@ template debug="false" hostspecific="false" language="C#" #> 2 | <#@ output extension=".Generated.cs" #> 3 | <#@ Assembly Name="System.Core" #> 4 | <#@ Import Namespace="System.Linq" #> 5 | // Copyright (c) 2007, Clarius Consulting, Manas Technology Solutions, InSTEDD, and Contributors. 6 | // All rights reserved. Licensed under the BSD 3-Clause License; see License.txt. 7 | 8 | using System; 9 | using System.ComponentModel; 10 | using Moq.Language.Flow; 11 | 12 | namespace Moq.Language 13 | { 14 | partial interface IReturns 15 | { <# 16 | for (var typeCount = 2; typeCount <= GenericTypeMax; typeCount++) 17 | { 18 | var typeList = GetGenericList(typeCount, GenericTypeFormat); 19 | #> 20 | 21 | /// 22 | /// Specifies a function that will calculate the value to return from the method, 23 | /// retrieving the arguments for the invocation. 24 | /// 25 | <# 26 | for (var typeIndex = 1; typeIndex <= typeCount; typeIndex++) 27 | { 28 | #> 29 | /// The type of the <#= ConvertToOrdinal(typeIndex) #> argument of the invoked method. 30 | <# 31 | } 32 | #> 33 | /// The function that will calculate the return value. 34 | /// Returns a calculated value which is evaluated lazily at the time of the invocation. 35 | /// 36 | /// 37 | /// The return value is calculated from the value of the actual method invocation arguments. 38 | /// Notice how the arguments are retrieved by simply declaring them as part of the lambda 39 | /// expression: 40 | /// 41 | /// 42 | /// mock.Setup(x => x.Execute( 43 | <# 44 | for (var typeIndex = 1; typeIndex < typeCount; typeIndex++) 45 | { 46 | #> 47 | /// It.IsAny<int>(), 48 | <# 49 | } 50 | #> 51 | /// It.IsAny<int>())) 52 | /// .Returns((<#= GetGenericList(typeCount, "int arg{0}") #>) => <#= GetGenericList(typeCount, "arg{0}", " + ") #>); 53 | /// 54 | /// 55 | IReturnsResult Returns<<#= typeList #>>(Func<<#= typeList #>, TResult> valueFunction); 56 | <# 57 | } 58 | #> 59 | } 60 | } 61 | <#@ Include File="GenericTypeParameters.tt" #> 62 | -------------------------------------------------------------------------------- /src/Moq/TypeMatcherAttribute.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2007, Clarius Consulting, Manas Technology Solutions, InSTEDD, and Contributors. 2 | // All rights reserved. Licensed under the BSD 3-Clause License; see License.txt. 3 | 4 | using System; 5 | 6 | namespace Moq 7 | { 8 | /// 9 | /// Marks a type as a type matcher, optionally specifying another type that will perform the matching. 10 | /// 11 | /// Type matchers preferably implement themselves. Use the parameterized form of this attribute 12 | /// where this is not possible, such as when the type matcher needs to be a or 13 | /// type in order to satisfy generic type constraints of the method where it is used. 14 | /// 15 | /// 16 | [AttributeUsage(AttributeTargets.Class | AttributeTargets.Delegate | AttributeTargets.Enum | AttributeTargets.Interface | AttributeTargets.Struct, AllowMultiple = false, Inherited = true)] 17 | public class TypeMatcherAttribute : Attribute 18 | { 19 | private readonly Type type; 20 | 21 | /// 22 | /// Initializes a new instance of the class. 23 | /// 24 | /// Use this constructor overload if the type on which this attribute is placed implements itself. 25 | /// 26 | /// 27 | public TypeMatcherAttribute() 28 | { 29 | this.type = null; 30 | } 31 | 32 | /// 33 | /// Initializes a new instance of the class. 34 | /// 35 | /// Use this constructor overload if the type on which this attribute is placed does not implement . 36 | /// The specified type will instead provide the implementation of . 37 | /// 38 | /// 39 | /// The of a type that implements . 40 | public TypeMatcherAttribute(Type type) 41 | { 42 | if (type == null) 43 | { 44 | throw new ArgumentNullException(nameof(type)); 45 | } 46 | 47 | this.type = type; 48 | } 49 | 50 | internal Type Type => this.type; 51 | } 52 | } 53 | -------------------------------------------------------------------------------- /tests/Moq.Tests/SequentialActionExtensionsFixture.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2007, Clarius Consulting, Manas Technology Solutions, InSTEDD, and Contributors. 2 | // All rights reserved. Licensed under the BSD 3-Clause License; see License.txt. 3 | 4 | using System; 5 | 6 | using Xunit; 7 | 8 | namespace Moq.Tests 9 | { 10 | public class SequentialActionExtensionsFixture 11 | { 12 | [Fact] 13 | public void PerformSequence() 14 | { 15 | var mock = new Mock(); 16 | 17 | mock.SetupSequence(m => m.Do()) 18 | .Pass() 19 | .Throws() 20 | .Throws(new ArgumentException()); 21 | 22 | mock.Object.Do(); 23 | Assert.Throws(() => mock.Object.Do()); 24 | Assert.Throws(() => mock.Object.Do()); 25 | } 26 | 27 | [Fact] 28 | public void PerformSequenceWithThrowFirst() 29 | { 30 | var mock = new Mock(); 31 | 32 | mock.SetupSequence(m => m.Do()) 33 | .Throws() 34 | .Pass() 35 | .Throws(new ArgumentException()); 36 | 37 | Assert.Throws(() => mock.Object.Do()); 38 | mock.Object.Do(); 39 | Assert.Throws(() => mock.Object.Do()); 40 | } 41 | 42 | [Fact] 43 | public void PerformSequenceWithCalculatedExceptions() 44 | { 45 | var mock = new Mock(); 46 | 47 | mock.SetupSequence(m => m.Do()) 48 | .Pass() 49 | .Throws(() => new InvalidOperationException()) 50 | .Throws(() => new ArgumentException()); 51 | 52 | mock.Object.Do(); 53 | Assert.Throws(() => mock.Object.Do()); 54 | Assert.Throws(() => mock.Object.Do()); 55 | } 56 | 57 | [Fact] 58 | public void PerformSequenceWithThrowCalculatedExceptionFirst() 59 | { 60 | var mock = new Mock(); 61 | 62 | mock.SetupSequence(m => m.Do()) 63 | .Throws(() => new InvalidOperationException()) 64 | .Pass() 65 | .Throws(new ArgumentException()); 66 | 67 | Assert.Throws(() => mock.Object.Do()); 68 | mock.Object.Do(); 69 | Assert.Throws(() => mock.Object.Do()); 70 | } 71 | 72 | public interface IFoo 73 | { 74 | void Do(); 75 | } 76 | } 77 | } 78 | -------------------------------------------------------------------------------- /tests/Moq.Tests/DefaultValueProviderFixture.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2007, Clarius Consulting, Manas Technology Solutions, InSTEDD, and Contributors. 2 | // All rights reserved. Licensed under the BSD 3-Clause License; see License.txt. 3 | 4 | using System; 5 | using System.Reflection; 6 | 7 | using Xunit; 8 | 9 | namespace Moq.Tests 10 | { 11 | /// 12 | /// Tests for the abstract base class. 13 | /// 14 | public class DefaultValueProviderFixture 15 | { 16 | private static MethodInfo fooActionMethod = typeof(IFoo).GetMethod(nameof(IFoo.Action)); 17 | private static ParameterInfo fooActionMethodParameter = typeof(IFoo).GetMethod(nameof(IFoo.Action)).GetParameters()[0]; 18 | private static MethodInfo fooFuncMethod = typeof(IFoo).GetMethod(nameof(IFoo.Func)); 19 | 20 | private DefaultValueProvider defaultValueProvider; 21 | private Mock fooMock; 22 | 23 | public DefaultValueProviderFixture() 24 | { 25 | this.defaultValueProvider = new DefaultValueProviderStub(); 26 | this.fooMock = new Mock(); 27 | } 28 | 29 | [Fact] 30 | public void GetDefaultParameterValue_returns_same_value_as_GetDefaultValue_if_GetDefaultParameterValue_not_overridden() 31 | { 32 | var _ = this.fooMock; 33 | var parameter = fooActionMethodParameter; 34 | var expected = this.defaultValueProvider.GetDefaultValue(parameter.ParameterType, _); 35 | 36 | var actual = this.defaultValueProvider.GetDefaultParameterValue(parameter, _); 37 | 38 | Assert.Equal(expected, actual); 39 | } 40 | 41 | [Fact] 42 | public void GetDefaultReturnValue_returns_same_value_as_GetDefaultValue_if_GetDefaultReturnValue_not_overridden() 43 | { 44 | var _ = this.fooMock; 45 | var method = fooFuncMethod; 46 | var expected = this.defaultValueProvider.GetDefaultValue(method.ReturnType, _); 47 | 48 | var actual = this.defaultValueProvider.GetDefaultReturnValue(method, _); 49 | 50 | Assert.Equal(expected, actual); 51 | } 52 | 53 | public interface IFoo 54 | { 55 | void Action(object arg); 56 | object Func(); 57 | } 58 | 59 | private sealed class DefaultValueProviderStub : DefaultValueProvider 60 | { 61 | protected internal override object GetDefaultValue(Type type, Mock mock) 62 | { 63 | return 42; 64 | } 65 | } 66 | } 67 | } 68 | -------------------------------------------------------------------------------- /tests/Moq.Tests/EventHandlerTypesMustMatchFixture.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2007, Clarius Consulting, Manas Technology Solutions, InSTEDD, and Contributors. 2 | // All rights reserved. Licensed under the BSD 3-Clause License; see License.txt. 3 | 4 | using System; 5 | 6 | using Xunit; 7 | 8 | namespace Moq.Tests 9 | { 10 | public class EventHandlerTypesMustMatchFixture 11 | { 12 | [Fact] 13 | public void CLI_requires_event_handlers_to_have_the_exact_same_type() 14 | { 15 | var mouse = new Mouse(); 16 | var result = 2; 17 | 18 | mouse.LeftButtonClicked += new Action(_ => result += 3); 19 | mouse.LeftButtonClicked += new Action(_ => result *= 4); 20 | mouse.RaiseLeftButtonClicked(new LeftButton()); 21 | 22 | Assert.Equal(20, result); 23 | } 24 | 25 | [Fact] 26 | public void CLI_throws_if_event_handlers_do_not_have_the_exact_same_type() 27 | { 28 | var mouse = new Mouse(); 29 | mouse.LeftButtonClicked += new Action