diff --git a/Moq.VisualBasicTests/IssueReports.vb b/Moq.VisualBasicTests/IssueReports.vb index a520e286c..5bf3bfcda 100644 --- a/Moq.VisualBasicTests/IssueReports.vb +++ b/Moq.VisualBasicTests/IssueReports.vb @@ -5,25 +5,25 @@ Imports Xunit Public Class IssueReports - Public Class Issue278 + Public Class Issue278 - - Public Sub SetupsForPropertiesWithMultipleArgsDoNotOverwriteEachOther() - Dim mock As New Mock(Of ISimpleInterface)() + + Public Sub SetupsForPropertiesWithMultipleArgsDoNotOverwriteEachOther() + Dim mock As New Mock(Of ISimpleInterface)() - mock.Setup(Function(m) m.PropertyWithMultipleArgs(1, 1)).Returns(1) - mock.Setup(Function(m) m.PropertyWithMultipleArgs(1, 2)).Returns(2) + mock.Setup(Function(m) m.PropertyWithMultipleArgs(1, 1)).Returns(1) + mock.Setup(Function(m) m.PropertyWithMultipleArgs(1, 2)).Returns(2) - Assert.Equal(1, mock.Object.PropertyWithMultipleArgs(1, 1)) - Assert.Equal(2, mock.Object.PropertyWithMultipleArgs(1, 2)) + Assert.Equal(1, mock.Object.PropertyWithMultipleArgs(1, 1)) + Assert.Equal(2, mock.Object.PropertyWithMultipleArgs(1, 2)) - End Sub + End Sub - Public Interface ISimpleInterface + Public Interface ISimpleInterface - ReadOnly Property PropertyWithMultipleArgs(setting As Integer, setting2 As Integer) As Integer + ReadOnly Property PropertyWithMultipleArgs(setting As Integer, setting2 As Integer) As Integer - End Interface - End Class + End Interface + End Class End Class diff --git a/Moq.VisualBasicTests/Moq.VisualBasicTests.vbproj b/Moq.VisualBasicTests/Moq.VisualBasicTests.vbproj index 80f4023e6..399730333 100644 --- a/Moq.VisualBasicTests/Moq.VisualBasicTests.vbproj +++ b/Moq.VisualBasicTests/Moq.VisualBasicTests.vbproj @@ -1,119 +1,119 @@  - - - Debug - AnyCPU - {95F2E2B2-2E06-4AC7-A86F-9B1B6369D4AD} - Library - Moq.VisualBasicTests - Moq.VisualBasicTests - 512 - Windows - v4.5 - true - - - true - full - true - true - bin\Debug\ - Moq.VisualBasicTests.xml - 42016,41999,42017,42018,42019,42032,42036,42020,42021,42022 - - - pdbonly - false - true - true - bin\Release\ - Moq.VisualBasicTests.xml - 42016,41999,42017,42018,42019,42032,42036,42020,42021,42022 - - - On - - - Binary - - - On - - - On - - - - {1C91AC30-5977-4BE5-BA67-8EB186C03514} - Moq - - - - - - - - - - - - - - - - - - - - - - - - - True - Application.myapp - - - True - True - Resources.resx - - - True - Settings.settings - True - - - - - VbMyResourcesResXFileCodeGenerator - Resources.Designer.vb - My.Resources - Designer - - - - - MyApplicationCodeGenerator - Application.Designer.vb - - - SettingsSingleFileGenerator - My - Settings.Designer.vb - - - - - - - - + + + Debug + AnyCPU + {95F2E2B2-2E06-4AC7-A86F-9B1B6369D4AD} + Library + Moq.VisualBasicTests + Moq.VisualBasicTests + 512 + Windows + v4.5 + true + + + true + full + true + true + bin\Debug\ + Moq.VisualBasicTests.xml + 42016,41999,42017,42018,42019,42032,42036,42020,42021,42022 + + + pdbonly + false + true + true + bin\Release\ + Moq.VisualBasicTests.xml + 42016,41999,42017,42018,42019,42032,42036,42020,42021,42022 + + + On + + + Binary + + + On + + + On + + + + {1C91AC30-5977-4BE5-BA67-8EB186C03514} + Moq + + + + + + + + + + + + + + + + + + + + + + + + + True + Application.myapp + + + True + True + Resources.resx + + + True + Settings.settings + True + + + + + VbMyResourcesResXFileCodeGenerator + Resources.Designer.vb + My.Resources + Designer + + + + + MyApplicationCodeGenerator + Application.Designer.vb + + + SettingsSingleFileGenerator + My + Settings.Designer.vb + + + + + + + + \ No newline at end of file diff --git a/Moq.VisualBasicTests/project.json b/Moq.VisualBasicTests/project.json index 2ee5aadb0..873a5e03b 100644 --- a/Moq.VisualBasicTests/project.json +++ b/Moq.VisualBasicTests/project.json @@ -1,13 +1,13 @@ { - "dependencies": { - "Castle.Core": "4.0.0", - "xunit": "2.1.0", - "xunit.runner.visualstudio": "2.1.0" - }, - "frameworks": { - "net45": {} - }, - "runtimes": { - "win": {} - } + "dependencies": { + "Castle.Core": "4.0.0", + "xunit": "2.1.0", + "xunit.runner.visualstudio": "2.1.0" + }, + "frameworks": { + "net45": {} + }, + "runtimes": { + "win": {} + } } \ No newline at end of file diff --git a/Moq.nuspec b/Moq.nuspec index 774fb15a3..0e9dee16c 100644 --- a/Moq.nuspec +++ b/Moq.nuspec @@ -1,17 +1,17 @@  - - Moq - 4.6 - Moq: an enjoyable mocking library - Daniel Cazzulino, kzu - Daniel Cazzulino, Clarius Labs, kzu - https://raw.githubusercontent.com/moq/moq4/master/License.txt - https://github.com/moq/moq4 - false - Moq is the most popular and friendly mocking framework for .NET - moq tdd mocking mocks unittesting agile unittest - Version 4.5 + + Moq + 4.6 + Moq: an enjoyable mocking library + Daniel Cazzulino, kzu + Daniel Cazzulino, Clarius Labs, kzu + https://raw.githubusercontent.com/moq/moq4/master/License.txt + https://github.com/moq/moq4 + false + Moq is the most popular and friendly mocking framework for .NET + moq tdd mocking mocks unittesting agile unittest + Version 4.5 * Updated to .NET 4.5 * Dropped support for .NET < 4.5 and Silverlight * Remove ILMerge. Depend on Castle NuGet package instead. @@ -35,8 +35,7 @@ Version 4.1 * Feature request: It.IsIn(..), It.IsNotIn(...) * Corrected Verify method behavior for generic methods calls * Differentiate verification error from mock crash -* Fix: Adding (and removing) handlers for events declared on interfaces works -when CallBase = true. +* Fix: Adding (and removing) handlers for events declared on interfaces works when CallBase = true. * Update to latest Castle * Fix: Mock.Of (Functional Syntax) doesn't work on properties with non-public setters * Fix: Allow to use CallBase instead of Returns @@ -103,7 +102,6 @@ Version 3.0 * Fixed issue #97 on not being able to use SetupSet/VerifySet if property did not have a getter * Better integration with Pex (http://research.microsoft.com/en-us/projects/Pex/) * Various other minor fixes (#134, #135, #137, #138, #140, etc.) - Version 2.6 @@ -160,8 +158,8 @@ Version 1.4 Version 1.3 - * Added support for overriding expectations set previously on a Mock. Now adding a second expectation for the same method/property call will override the existing one. This facilitates setting up default expectations in a fixture setup and overriding when necessary in a specific test. - * Added support for mock verification. Both Verify and VerifyAll are provided for more flexibility (the former only verifies methods marked Verifiable) +* Added support for overriding expectations set previously on a Mock. Now adding a second expectation for the same method/property call will override the existing one. This facilitates setting up default expectations in a fixture setup and overriding when necessary in a specific test. +* Added support for mock verification. Both Verify and VerifyAll are provided for more flexibility (the former only verifies methods marked Verifiable) Version 1.2 @@ -175,44 +173,44 @@ Version 1.1 Version 1.0 * Initial release, initial documentation process in place, etc. - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - \ No newline at end of file + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/Moq.shfb b/Moq.shfb index b8ceb9744..66922dcca 100644 --- a/Moq.shfb +++ b/Moq.shfb @@ -1,119 +1,119 @@  - - - - - - - - - - - - - - - - - - - Root namespace of Moq (pronounced "Mock-you" or just "Mock"), the only mocking library for .NET developed from scratch to take full advantage of .NET 3.5 (i.e. Linq expression trees) and C# 3.0 features (i.e. lambda expressions) that make it the most productive, simple and refactoring-friendly mocking library available. + + + + + + + + + + + + + + + + + + + Root namespace of Moq (pronounced "Mock-you" or just "Mock"), the only mocking library for .NET developed from scratch to take full advantage of .NET 3.5 (i.e. Linq expression trees) and C# 3.0 features (i.e. lambda expressions) that make it the most productive, simple and refactoring-friendly mocking library available. <p> See the <a href="https://github.com/moq/moq4/wiki/Quickstart">online quickstarts</a> for more examples than those available in this code documentation. </p> <p>The Mock&lt;T&gt; class is the core of the library, so it's a good place to start.</p> You can also read <a href="http://blogsearch.google.com/blogsearch?q=moq+mock">blog entries</a> from around the world about Moq. - This namespace defines the interfaces that contain the methods available in Moq fluent API, such as Setup, Callback, Returns, Throws, etc. + This namespace defines the interfaces that contain the methods available in Moq fluent API, such as Setup, Callback, Returns, Throws, etc. <p> Review the documentation of the available methods on these interfaces for code examples. The way these interfaces are composed, grouped and made visible at different stages during an expectation (i.e. Verifiable is the last "verb" and can't be specified before the Returns) is internal but the API will naturally lead you to the proper way of using it, so don't worry too much about who (and where) exposes these language interfaces. They will show up in Intellisense when it's appropriate. </p><p> Do use their documentation to learn about options (especially when there are several overloads available) that may be a better fit for a particular scenario.</p> - - Provides pre-built mocks for testing ASP.NET MVC applications. - - Importing this namespace will enable the Protected() method on mocks, enabling expectations on protected members by specifying the member name as a string. - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - Summary, Parameter, AutoDocumentCtors, Namespace - InheritedMembers, Protected, SealedProtected - - - ..\build\Help\ - - - True - True - - Help1xAndWebsite - False - 4.0.30319 - False - False - False - - Moq - Moq - en-US - - - moqdisc@googlegroups.com - - - - Local - Msdn - Blank - vs2005 - HashedMemberName - CSharp - False - True - False - Hierarchical - True - ms.vsipcc+, ms.vsexpresscc+ - 1.0.0.0 - AboveNamespaces - \ No newline at end of file + + Provides pre-built mocks for testing ASP.NET MVC applications. + + Importing this namespace will enable the Protected() method on mocks, enabling expectations on protected members by specifying the member name as a string. + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Summary, Parameter, AutoDocumentCtors, Namespace + InheritedMembers, Protected, SealedProtected + + + ..\build\Help\ + + + True + True + + Help1xAndWebsite + False + 4.0.30319 + False + False + False + + Moq + Moq + en-US + + + moqdisc@googlegroups.com + + + + Local + Msdn + Blank + vs2005 + HashedMemberName + CSharp + False + True + False + Hierarchical + True + ms.vsipcc+, ms.vsexpresscc+ + 1.0.0.0 + AboveNamespaces + diff --git a/Moq.shfbproj b/Moq.shfbproj index f94307524..924908116 100644 --- a/Moq.shfbproj +++ b/Moq.shfbproj @@ -1,155 +1,155 @@  - - - Debug - AnyCPU - 2.0 - {625556c0-8f59-4f6e-a1cb-531db1cc0935} - 1.9.0.0 - - Documentation - Documentation - Documentation - - ..\build\Help\ - Moq - en-US - - - - - - - - - - - - - - + + + Debug + AnyCPU + 2.0 + {625556c0-8f59-4f6e-a1cb-531db1cc0935} + 1.9.0.0 + + Documentation + Documentation + Documentation + + ..\build\Help\ + Moq + en-US + + + + + + + + + + + + + + - + - + - - - Summary, AutoDocumentCtors, Namespace - InheritedMembers, Protected, SealedProtected - ..\build\HTML Help Workshop\ - - - ..\build\Sandcastle\ - - - - - HtmlHelp1, Website - 4.0.30319 - Moq - moqdisc%40googlegroups.com - vs2005 - HashedMemberName - CSharp - - - - - - - - - - - + + + Summary, AutoDocumentCtors, Namespace + InheritedMembers, Protected, SealedProtected + ..\build\HTML Help Workshop\ + + + ..\build\Sandcastle\ + + + + + HtmlHelp1, Website + 4.0.30319 + Moq + moqdisc%40googlegroups.com + vs2005 + HashedMemberName + CSharp + + + + + + + + + + + {@HelpFormatOutputPaths} + Attributes: + Stylesheet file (required) + Script file (required) + "Copy" image file (required) -->{@HelpFormatOutputPaths} {@CachedFrameworkCommentList} {@CommentFileList} - + - - + + - - - - - - - - - - - - - - - - Root namespace of Moq (pronounced "Mock-you" or just "Mock"), the only mocking library for .NET developed from scratch to take full advantage of .NET 3.5 (i.e. Linq expression trees) and C# 3.0 features (i.e. lambda expressions) that make it the most productive, simple and refactoring-friendly mocking library available. + + + + + + + + + + + + + + + + Root namespace of Moq (pronounced "Mock-you" or just "Mock"), the only mocking library for .NET developed from scratch to take full advantage of .NET 3.5 (i.e. Linq expression trees) and C# 3.0 features (i.e. lambda expressions) that make it the most productive, simple and refactoring-friendly mocking library available. <p> See the <a href="https://github.com/moq/moq4/wiki/Quickstart">online quickstarts</a> for more examples than those available in this code documentation. </p> <p>The Mock&lt;T&gt; class is the core of the library, so it's a good place to start.</p> You can also read <a href="http://blogsearch.google.com/blogsearch?q=moq+mock">blog entries</a> from around the world about Moq. - This namespace defines the interfaces that contain the methods available in Moq fluent API, such as Setup, Callback, Returns, Throws, etc. + This namespace defines the interfaces that contain the methods available in Moq fluent API, such as Setup, Callback, Returns, Throws, etc. <p> Review the documentation of the available methods on these interfaces for code examples. The way these interfaces are composed, grouped and made visible at different stages during an expectation (i.e. Verifiable is the last "verb" and can't be specified before the Returns) is internal but the API will naturally lead you to the proper way of using it, so don't worry too much about who (and where) exposes these language interfaces. They will show up in Intellisense when it's appropriate. </p><p> Do use their documentation to learn about options (especially when there are several overloads available) that may be a better fit for a particular scenario.</p> - - Provides pre-built mocks for testing ASP.NET MVC applications. - - Importing this namespace will enable the Protected() method on mocks, enabling expectations on protected members by specifying the member name as a string. - - - - - - - - - - - - - - - - - - - - - - - \ No newline at end of file + + Provides pre-built mocks for testing ASP.NET MVC applications. + + Importing this namespace will enable the Protected() method on mocks, enabling expectations on protected members by specifying the member name as a string. + + + + + + + + + + + + + + + + + + + + + + + diff --git a/NuGet.Restore.targets b/NuGet.Restore.targets index be147f359..7dafd997f 100644 --- a/NuGet.Restore.targets +++ b/NuGet.Restore.targets @@ -1,92 +1,91 @@ - - $(MSBuildThisFileDirectory).nuget - + + $(MSBuildThisFileDirectory).nuget + - - $(NuGetPath)\NuGet.exe - $(LocalAppData)\NuGet\NuGet.exe - + + $(NuGetPath)\NuGet.exe + $(LocalAppData)\NuGet\NuGet.exe + - - nuget - + + nuget + - - - - - - - - Restore - - - + + + + - + + + Restore + + + - - - + - - - - $([System.IO.Path]::GetDirectoryName('$(SolutionPath)')) - - - - - <_NuGet>$(NuGet.Replace('$(RestoreDir)', '').TrimStart('/').TrimStart('\')) - - - - - - - - - - - - - - + + + - - <_RestoreSolution Condition=" '$(OS)' != 'Unix' ">$(_RestoreSolution.Replace('$(RestoreDir)', '').TrimStart('/').TrimStart('\')) - <_RestoreOutput Condition=" '$(OS)' != 'Unix' And '$(_RestoreOutput)' != ''">$(_RestoreOutput.Replace('$(RestoreDir)', '').TrimStart('/').TrimStart('\')) - - <_RestoreCommand Condition=" '$(_RestoreCommand)' == '' ">Restore - + + + + $([System.IO.Path]::GetDirectoryName('$(SolutionPath)')) + + + + + <_NuGet>$(NuGet.Replace('$(RestoreDir)', '').TrimStart('/').TrimStart('\')) + - + + + + + + + + + + + + - - + + <_RestoreSolution Condition=" '$(OS)' != 'Unix' ">$(_RestoreSolution.Replace('$(RestoreDir)', '').TrimStart('/').TrimStart('\')) + <_RestoreOutput Condition=" '$(OS)' != 'Unix' And '$(_RestoreOutput)' != ''">$(_RestoreOutput.Replace('$(RestoreDir)', '').TrimStart('/').TrimStart('\')) + + <_RestoreCommand Condition=" '$(_RestoreCommand)' == '' ">Restore + + - - - %WINDIR%\System32\WindowsPowerShell\v1.0\powershell.exe - + + - - - - - - + + + %WINDIR%\System32\WindowsPowerShell\v1.0\powershell.exe + + + + + + + + diff --git a/README.md b/README.md index c3d47c10e..7d6c0210e 100644 --- a/README.md +++ b/README.md @@ -88,8 +88,6 @@ Moq offers the following features: * Intercept and raise events on mocks * Intuitive support for out/ref arguments - - We appreciate deeply any [feedback](http://moq.uservoice.com/) that you may have! ![OhLoh](http://www.ohloh.net/p/moq/widgets/project_thin_badge.gif) diff --git a/ReleaseNotes.md b/ReleaseNotes.md index fb6ee826b..8ae60843a 100644 --- a/ReleaseNotes.md +++ b/ReleaseNotes.md @@ -1,13 +1,16 @@ Version 4.5 + * Updated to .NET 4.5 * Dropped support for .NET < 4.5 and Silverlight * Remove ILMerge. Depend on Castle NuGet package instead. Version 4.3 + * Added support for Roslyn * Automatically add implemented interfaces to mock Version 4.2 + * Improved support for async APIs by making default value a completed task * Added support for async Returns and Throws * Improved mock invocation sequence testing @@ -15,6 +18,7 @@ Version 4.2 * Added support for named mocks Version 4.1 + * Added covariant IMock<out T> interface to Mock<T> * Added It.IsNotNull<T> * Fix: 'NullReferenceException when subscribing to an event' @@ -22,8 +26,7 @@ Version 4.1 * Feature request: It.IsIn(..), It.IsNotIn(...) * Corrected Verify method behavior for generic methods calls * Differentiate verification error from mock crash -* Fix: Adding (and removing) handlers for events declared on interfaces works -when CallBase = true. +* Fix: Adding (and removing) handlers for events declared on interfaces works when CallBase = true. * Update to latest Castle * Fix: Mock.Of (Functional Syntax) doesn't work on properties with non-public setters * Fix: Allow to use CallBase instead of Returns @@ -31,6 +34,7 @@ when CallBase = true. * Capability of mocking delegates (event handlers) Version 4.0 + * Linq to Mocks: Mock.Of<T>(x => x.Id == 23 && x.Title == "Rocks!") * Fixed issues: * 87 BadImageFormatException when using a mock with a Visual Studio generated Accessor object @@ -90,7 +94,6 @@ Version 3.0 * Fixed issue #97 on not being able to use SetupSet/VerifySet if property did not have a getter * Better integration with Pex (http://research.microsoft.com/en-us/projects/Pex/) * Various other minor fixes (#134, #135, #137, #138, #140, etc.) - Version 2.6 @@ -121,7 +124,6 @@ Version 2.5 * Added support for implementing and setting expectations and verifying additional interfaces in the mock, via the new mock.As<TInterface>() method (thanks Fernando Simonazzi!) * Improved argument type matching for Is/IsAny (thanks Jeremy.Skinner!) - Version 2.0 * Refactored fluent API on mocks. This may cause some existing tests to fail, but the fix is trivial (just reorder the calls to Callback, Returns and Verifiable) @@ -131,7 +133,6 @@ Version 2.0 * Added support for creating MBROs with protected constructors * Loose mocks now return default empty arrays and IEnumerables instead of nulls - Version 1.5.1 * Refactored MockFactory to make it simpler and more explicit to use with regards to verification. Thanks Garry Shutler for the feedback! @@ -157,8 +158,8 @@ Version 1.2 Version 1.1 * Merged branch for dynamic types. Now Moq is based on Castle DynamicProxy2 to support a wider range of mock targets. -* Added ILMerge so that Castle libraries are merged into Moq assembly (no need for external references and avoid conflicts) +* Added ILMerge so that Castle libraries are merged into Moq assembly (no need for external references and avoid conflicts) Version 1.0 -* Initial release, initial documentation process in place, etc. +* Initial release, initial documentation process in place, etc. diff --git a/Samples/ProductsMvcSample/Source/ProductsMvcSample/ProductsMvcSample.csproj b/Samples/ProductsMvcSample/Source/ProductsMvcSample/ProductsMvcSample.csproj index 7beae3166..4e435deba 100644 --- a/Samples/ProductsMvcSample/Source/ProductsMvcSample/ProductsMvcSample.csproj +++ b/Samples/ProductsMvcSample/Source/ProductsMvcSample/ProductsMvcSample.csproj @@ -1,144 +1,144 @@  - - Debug - AnyCPU - 9.0.30729 - 2.0 - {766F76DC-B97D-41FE-A6D8-F039EAB8533D} - {349c5851-65df-11da-9384-00065b846f21};{fae04ec0-301f-11d3-bf4b-00c04f79efbc} - Library - Properties - ProductsMvcSample - ProductsMvcSample - v3.5 - - - true - full - false - bin\ - DEBUG;TRACE - prompt - 4 - - - pdbonly - true - bin\ - TRACE - prompt - 4 - - - - False - ..\..\..\Lib\Microsoft.Web.Mvc.dll - - - False - ..\..\..\Lib\Moq.dll - - - - - 3.5 - - - False - ..\..\..\Lib\System.Web.Abstractions.dll - 3.5 - - - False - - - False - ..\..\..\Lib\System.Web.Mvc.dll - - - False - ..\..\..\Lib\System.Web.Routing.dll - 3.5 - - - 3.5 - - - - - - - - - - - - - - - - - - Default.aspx - ASPXCodeBehind - - - Global.asax - - - - - - - - Welcome.aspx - ASPXCodeBehind - - - ProductsList.aspx - ASPXCodeBehind - - - Site.Master - ASPXCodeBehind - - - - - - - - - - - - - - - - - - - - False - True - 64701 - / - - - False - False - - - False - - - - - \ No newline at end of file + + Debug + AnyCPU + 9.0.30729 + 2.0 + {766F76DC-B97D-41FE-A6D8-F039EAB8533D} + {349c5851-65df-11da-9384-00065b846f21};{fae04ec0-301f-11d3-bf4b-00c04f79efbc} + Library + Properties + ProductsMvcSample + ProductsMvcSample + v3.5 + + + true + full + false + bin\ + DEBUG;TRACE + prompt + 4 + + + pdbonly + true + bin\ + TRACE + prompt + 4 + + + + False + ..\..\..\Lib\Microsoft.Web.Mvc.dll + + + False + ..\..\..\Lib\Moq.dll + + + + + 3.5 + + + False + ..\..\..\Lib\System.Web.Abstractions.dll + 3.5 + + + False + + + False + ..\..\..\Lib\System.Web.Mvc.dll + + + False + ..\..\..\Lib\System.Web.Routing.dll + 3.5 + + + 3.5 + + + + + + + + + + + + + + + + + + Default.aspx + ASPXCodeBehind + + + Global.asax + + + + + + + + Welcome.aspx + ASPXCodeBehind + + + ProductsList.aspx + ASPXCodeBehind + + + Site.Master + ASPXCodeBehind + + + + + + + + + + + + + + + + + + + + False + True + 64701 + / + + + False + False + + + False + + + + + diff --git a/Samples/ProductsMvcSample/Source/ProductsMvcSample/Views/Home/Welcome.aspx b/Samples/ProductsMvcSample/Source/ProductsMvcSample/Views/Home/Welcome.aspx index 567a4aacf..d7ca3d408 100644 --- a/Samples/ProductsMvcSample/Source/ProductsMvcSample/Views/Home/Welcome.aspx +++ b/Samples/ProductsMvcSample/Source/ProductsMvcSample/Views/Home/Welcome.aspx @@ -7,5 +7,5 @@
  • <%= Html.ActionLink(c => c.Category(1), "View Category 1") %>
  • <%= Html.ActionLink(c => c.Category(2), "View Category 2") %>
  • -
+ diff --git a/Samples/ProductsMvcSample/Source/ProductsMvcSample/Views/Products/ProductsList.aspx b/Samples/ProductsMvcSample/Source/ProductsMvcSample/Views/Products/ProductsList.aspx index 208f825c6..ead0519fc 100644 --- a/Samples/ProductsMvcSample/Source/ProductsMvcSample/Views/Products/ProductsList.aspx +++ b/Samples/ProductsMvcSample/Source/ProductsMvcSample/Views/Products/ProductsList.aspx @@ -8,7 +8,7 @@
    <% foreach (var product in ViewData.Model.Products) { %> -
  • <%= product.Name %>
  • +
  • <%= product.Name %>
  • <% } %>
diff --git a/Samples/ProductsMvcSample/Source/ProductsMvcSample/Views/Shared/Site.Master b/Samples/ProductsMvcSample/Source/ProductsMvcSample/Views/Shared/Site.Master index 52558f292..c85635c85 100644 --- a/Samples/ProductsMvcSample/Source/ProductsMvcSample/Views/Shared/Site.Master +++ b/Samples/ProductsMvcSample/Source/ProductsMvcSample/Views/Shared/Site.Master @@ -4,16 +4,16 @@ - Untitled Page - - + Untitled Page + +
Products Catalog Sample (Tested by MoQ).
-
- - - -
+
+ + + +
diff --git a/Samples/ProductsMvcSample/Source/ProductsMvcSample/Web.config b/Samples/ProductsMvcSample/Source/ProductsMvcSample/Web.config index c20bc50ba..24c50ff1d 100644 --- a/Samples/ProductsMvcSample/Source/ProductsMvcSample/Web.config +++ b/Samples/ProductsMvcSample/Source/ProductsMvcSample/Web.config @@ -1,11 +1,11 @@ @@ -30,11 +30,11 @@ + Set compilation debug="true" to insert debugging + symbols into the compiled page. Because this + affects performance, set this value to true only + during development. + --> @@ -48,24 +48,24 @@ + The section enables configuration + of the security authentication mode used by + ASP.NET to identify an incoming user. + --> + The section enables configuration + of what to do if/when an unhandled error occurs + during the execution of a request. Specifically, + it enables developers to configure html error pages + to be displayed in place of a error stack trace. + + + + + + --> @@ -99,13 +99,13 @@ + type="Microsoft.CSharp.CSharpCodeProvider, System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"> + type="Microsoft.VisualBasic.VBCodeProvider, System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"> @@ -116,8 +116,8 @@ @@ -135,9 +135,9 @@ + type="System.Web.Script.Services.ScriptHandlerFactory, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/> + type="System.Web.Script.Services.ScriptHandlerFactory, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/> diff --git a/Samples/ProductsMvcSample/UnitTests/ProductsMvcSample.Tests/Controllers/ProductsControllerFixture.cs b/Samples/ProductsMvcSample/UnitTests/ProductsMvcSample.Tests/Controllers/ProductsControllerFixture.cs index 954dcf539..aa85be1d3 100644 --- a/Samples/ProductsMvcSample/UnitTests/ProductsMvcSample.Tests/Controllers/ProductsControllerFixture.cs +++ b/Samples/ProductsMvcSample/UnitTests/ProductsMvcSample.Tests/Controllers/ProductsControllerFixture.cs @@ -68,10 +68,10 @@ public void CategoryRendersRendersViewDataWithProdcutsListing() catalogService.Setup(c => c .GetProducts(2)) .Returns(new List - { - new Product { Id = 4 , Name = "Foo"}, - new Product { Id = 7 , Name = "Bar"} - }); + { + new Product { Id = 4 , Name = "Foo" }, + new Product { Id = 7 , Name = "Bar" } + }); // Target object var controller = new ProductsController(catalogService.Object); diff --git a/Samples/ProductsMvcSample/UnitTests/ProductsMvcSample.Tests/ProductsMvcSample.Tests.csproj b/Samples/ProductsMvcSample/UnitTests/ProductsMvcSample.Tests/ProductsMvcSample.Tests.csproj index be8f8b402..dbec457c6 100644 --- a/Samples/ProductsMvcSample/UnitTests/ProductsMvcSample.Tests/ProductsMvcSample.Tests.csproj +++ b/Samples/ProductsMvcSample/UnitTests/ProductsMvcSample.Tests/ProductsMvcSample.Tests.csproj @@ -1,94 +1,94 @@  - - Debug - AnyCPU - 9.0.30729 - 2.0 - {0BB61A7C-2791-45EC-A7A5-E2F525CAFA72} - Library - Properties - ProductsMvcSample.Tests - ProductsMvcSample.Tests - v3.5 - 512 - - - true - full - false - bin\Debug\ - DEBUG;TRACE - prompt - 4 - - - pdbonly - true - bin\Release\ - TRACE - prompt - 4 - - - - False - ..\..\..\Lib\Moq.dll - - - False - ..\..\..\Lib\nunit.framework.dll - - - - 3.5 - - - - False - ..\..\..\Lib\System.Web.Abstractions.dll - 3.5 - - - False - - - False - ..\..\..\Lib\System.Web.Mvc.dll - - - False - ..\..\..\Lib\System.Web.Routing.dll - 3.5 - - - 3.5 - - - - - - - - Code - - - - Code - - - - - {766F76DC-B97D-41FE-A6D8-F039EAB8533D} - ProductsMvcSample - - - - + + Debug + AnyCPU + 9.0.30729 + 2.0 + {0BB61A7C-2791-45EC-A7A5-E2F525CAFA72} + Library + Properties + ProductsMvcSample.Tests + ProductsMvcSample.Tests + v3.5 + 512 + + + true + full + false + bin\Debug\ + DEBUG;TRACE + prompt + 4 + + + pdbonly + true + bin\Release\ + TRACE + prompt + 4 + + + + False + ..\..\..\Lib\Moq.dll + + + False + ..\..\..\Lib\nunit.framework.dll + + + + 3.5 + + + + False + ..\..\..\Lib\System.Web.Abstractions.dll + 3.5 + + + False + + + False + ..\..\..\Lib\System.Web.Mvc.dll + + + False + ..\..\..\Lib\System.Web.Routing.dll + 3.5 + + + 3.5 + + + + + + + + Code + + + + Code + + + + + {766F76DC-B97D-41FE-A6D8-F039EAB8533D} + ProductsMvcSample + + + + \ No newline at end of file diff --git a/Samples/StoreSample/Source/Services/CatalogService.cs b/Samples/StoreSample/Source/Services/CatalogService.cs index f0bb4251b..44e7c9750 100644 --- a/Samples/StoreSample/Source/Services/CatalogService.cs +++ b/Samples/StoreSample/Source/Services/CatalogService.cs @@ -4,6 +4,5 @@ namespace Store { public class CatalogService { - } } diff --git a/Samples/StoreSample/Source/Store.csproj b/Samples/StoreSample/Source/Store.csproj index 05711c6b2..f7bc6f375 100644 --- a/Samples/StoreSample/Source/Store.csproj +++ b/Samples/StoreSample/Source/Store.csproj @@ -1,58 +1,58 @@  - - Debug - AnyCPU - 9.0.30729 - 2.0 - {BDF061BD-AD85-4BE6-9661-C24504896633} - Library - Properties - Store - Store - v3.5 - 512 - - - true - full - false - bin\Debug\ - DEBUG;TRACE - prompt - 4 - - - pdbonly - true - bin\Release\ - TRACE - prompt - 4 - - - - - 3.5 - - - - - - - - - - - - - - - - \ No newline at end of file + + Debug + AnyCPU + 9.0.30729 + 2.0 + {BDF061BD-AD85-4BE6-9661-C24504896633} + Library + Properties + Store + Store + v3.5 + 512 + + + true + full + false + bin\Debug\ + DEBUG;TRACE + prompt + 4 + + + pdbonly + true + bin\Release\ + TRACE + prompt + 4 + + + + + 3.5 + + + + + + + + + + + + + + + + diff --git a/Samples/StoreSample/UnitTests/Store.Tests.csproj b/Samples/StoreSample/UnitTests/Store.Tests.csproj index 7c7f62c2f..f9c39109b 100644 --- a/Samples/StoreSample/UnitTests/Store.Tests.csproj +++ b/Samples/StoreSample/UnitTests/Store.Tests.csproj @@ -1,65 +1,65 @@  - - Debug - AnyCPU - 9.0.30729 - 2.0 - {ACA76E67-0611-4415-927D-64FFB9C462A5} - Library - Properties - Store.Tests - Store.Tests - v3.5 - 512 - - - true - full - false - bin\Debug\ - DEBUG;TRACE - prompt - 4 - - - pdbonly - true - bin\Release\ - TRACE - prompt - 4 - - - - False - ..\..\Lib\Moq.dll - - - False - ..\..\Lib\nunit.framework.dll - - - - 3.5 - - - - - - - - - {BDF061BD-AD85-4BE6-9661-C24504896633} - Store - - - - + + Debug + AnyCPU + 9.0.30729 + 2.0 + {ACA76E67-0611-4415-927D-64FFB9C462A5} + Library + Properties + Store.Tests + Store.Tests + v3.5 + 512 + + + true + full + false + bin\Debug\ + DEBUG;TRACE + prompt + 4 + + + pdbonly + true + bin\Release\ + TRACE + prompt + 4 + + + + False + ..\..\Lib\Moq.dll + + + False + ..\..\Lib\nunit.framework.dll + + + + 3.5 + + + + + + + + + {BDF061BD-AD85-4BE6-9661-C24504896633} + Store + + + + \ No newline at end of file diff --git a/Source/AdvancedMatcherAttribute.cs b/Source/AdvancedMatcherAttribute.cs index d44fe863a..f9fcb1147 100644 --- a/Source/AdvancedMatcherAttribute.cs +++ b/Source/AdvancedMatcherAttribute.cs @@ -68,4 +68,4 @@ public IMatcher CreateMatcher() } } } -} \ No newline at end of file +} diff --git a/Source/AsInterface.cs b/Source/AsInterface.cs index caa757d66..4230bb610 100644 --- a/Source/AsInterface.cs +++ b/Source/AsInterface.cs @@ -100,4 +100,4 @@ public override Mock As() return this.owner.As(); } } -} \ No newline at end of file +} diff --git a/Source/Capture.cs b/Source/Capture.cs index e655d4a0d..4a18ac0f4 100644 --- a/Source/Capture.cs +++ b/Source/Capture.cs @@ -44,75 +44,75 @@ namespace Moq { - /// - /// Allows to create parameter captures in setup expressions. - /// - public static class Capture - { - /// - /// Creates a parameter capture that will store values in a collection. - /// - /// The captured object type - /// The collection that will store captured parameter values - /// - /// Arrange code: - /// - /// var parameters = new List{string}(); - /// mock.Setup(x => x.DoSomething(Capture.In(parameters))); - /// - /// Assert code: - /// - /// Assert.Equal("Hello!", parameters.Single()); - /// - /// - public static T In(ICollection collection) - { - var match = new CaptureMatch(collection.Add); - return With(match); - } + /// + /// Allows to create parameter captures in setup expressions. + /// + public static class Capture + { + /// + /// Creates a parameter capture that will store values in a collection. + /// + /// The captured object type + /// The collection that will store captured parameter values + /// + /// Arrange code: + /// + /// var parameters = new List{string}(); + /// mock.Setup(x => x.DoSomething(Capture.In(parameters))); + /// + /// Assert code: + /// + /// Assert.Equal("Hello!", parameters.Single()); + /// + /// + public static T In(ICollection collection) + { + var match = new CaptureMatch(collection.Add); + return With(match); + } - /// - /// Creates a parameter capture that will store specific values in a collection. - /// - /// The captured object type - /// The collection that will store captured parameter values - /// A predicate used to filter captured parameters - /// - /// Arrange code: - /// - /// var parameters = new List{string}(); - /// mock.Setup(x => x.DoSomething(Capture.In(parameters, p => p.StartsWith("W")))); - /// - /// Assert code: - /// - /// Assert.Equal("Hello!", parameters.Single()); - /// - /// - public static T In(IList collection, Expression> predicate) - { - var match = new CaptureMatch(collection.Add, predicate); - return With(match); - } + /// + /// Creates a parameter capture that will store specific values in a collection. + /// + /// The captured object type + /// The collection that will store captured parameter values + /// A predicate used to filter captured parameters + /// + /// Arrange code: + /// + /// var parameters = new List{string}(); + /// mock.Setup(x => x.DoSomething(Capture.In(parameters, p => p.StartsWith("W")))); + /// + /// Assert code: + /// + /// Assert.Equal("Hello!", parameters.Single()); + /// + /// + public static T In(IList collection, Expression> predicate) + { + var match = new CaptureMatch(collection.Add, predicate); + return With(match); + } - /// - /// Creates a parameter capture using specified . - /// - /// The captured object type - /// - /// Arrange code: - /// - /// var capturedValue = string.Empty; - /// var match = new CaptureMatch{string}(x => capturedValue = x); - /// mock.Setup(x => x.DoSomething(Capture.With(match))); - /// - /// Assert code: - /// - /// Assert.Equal("Hello!", capturedValue); - /// - /// - public static T With(CaptureMatch match) - { - return Match.Create(match); - } - } -} \ No newline at end of file + /// + /// Creates a parameter capture using specified . + /// + /// The captured object type + /// + /// Arrange code: + /// + /// var capturedValue = string.Empty; + /// var match = new CaptureMatch{string}(x => capturedValue = x); + /// mock.Setup(x => x.DoSomething(Capture.With(match))); + /// + /// Assert code: + /// + /// Assert.Equal("Hello!", capturedValue); + /// + /// + public static T With(CaptureMatch match) + { + return Match.Create(match); + } + } +} diff --git a/Source/CaptureMatch.cs b/Source/CaptureMatch.cs index 517b0cad3..30870866c 100644 --- a/Source/CaptureMatch.cs +++ b/Source/CaptureMatch.cs @@ -43,51 +43,51 @@ namespace Moq { - /// - /// Allows creation custom matchers that can be used on setups to capture parameter values. - /// - /// - public class CaptureMatch : Match - { - /// - /// Initializes an instance of the capture match. - /// - /// An action to run on captured value - public CaptureMatch(Action captureCallback) - : base(CreatePredicate(captureCallback), () => It.IsAny()) - { - } + /// + /// Allows creation custom matchers that can be used on setups to capture parameter values. + /// + /// + public class CaptureMatch : Match + { + /// + /// Initializes an instance of the capture match. + /// + /// An action to run on captured value + public CaptureMatch(Action captureCallback) + : base(CreatePredicate(captureCallback), () => It.IsAny()) + { + } - /// - /// Initializes an instance of the capture match. - /// - /// An action to run on captured value - /// A predicate used to filter captured parameters - public CaptureMatch(Action captureCallback, Expression> predicate) - : base(CreatePredicate(captureCallback, predicate), () => It.Is(predicate)) - { - } + /// + /// Initializes an instance of the capture match. + /// + /// An action to run on captured value + /// A predicate used to filter captured parameters + public CaptureMatch(Action captureCallback, Expression> predicate) + : base(CreatePredicate(captureCallback, predicate), () => It.Is(predicate)) + { + } - private static Predicate CreatePredicate(Action captureCallback) - { - return value => - { - captureCallback.Invoke(value); - return true; - }; - } + private static Predicate CreatePredicate(Action captureCallback) + { + return value => + { + captureCallback.Invoke(value); + return true; + }; + } - private static Predicate CreatePredicate(Action captureCallback, Expression> predicate) - { - var predicateDelegate = predicate.Compile(); - return value => - { - var matches = predicateDelegate.Invoke(value); - if (matches) - captureCallback.Invoke(value); + private static Predicate CreatePredicate(Action captureCallback, Expression> predicate) + { + var predicateDelegate = predicate.Compile(); + return value => + { + var matches = predicateDelegate.Invoke(value); + if (matches) + captureCallback.Invoke(value); - return matches; - }; - } - } -} \ No newline at end of file + return matches; + }; + } + } +} diff --git a/Source/ConditionalContext.cs b/Source/ConditionalContext.cs index 88117868b..9f1a60045 100644 --- a/Source/ConditionalContext.cs +++ b/Source/ConditionalContext.cs @@ -82,4 +82,4 @@ public ISetup SetupSet(Action setterExpression) return Mock.SetupSet(mock, setterExpression, this.condition); } } -} \ No newline at end of file +} diff --git a/Source/Evaluator.cs b/Source/Evaluator.cs index 9647091f6..37febedbe 100644 --- a/Source/Evaluator.cs +++ b/Source/Evaluator.cs @@ -163,4 +163,4 @@ public override Expression Visit(Expression expression) } } } -} \ No newline at end of file +} diff --git a/Source/ExpressionExtensions.cs b/Source/ExpressionExtensions.cs index dd6764fb7..2aaa96565 100644 --- a/Source/ExpressionExtensions.cs +++ b/Source/ExpressionExtensions.cs @@ -296,4 +296,4 @@ protected override Expression VisitUnary(UnaryExpression expression) public Expression Expression { get; private set; } } } -} \ No newline at end of file +} diff --git a/Source/ExpressionStringBuilder.cs b/Source/ExpressionStringBuilder.cs index e1dea4047..b6d9eb436 100644 --- a/Source/ExpressionStringBuilder.cs +++ b/Source/ExpressionStringBuilder.cs @@ -351,13 +351,13 @@ private void ToStringMethodCall(MethodCallExpression node) } else if (node.Method.IsPropertyGetter()) { - this.builder.Append(".").Append(node.Method.Name.Substring(4)); - if (node.Arguments.Count > paramFrom) - { - this.builder.Append("["); - AsCommaSeparatedValues(node.Arguments.Skip(paramFrom), ToString); - this.builder.Append("]"); - } + this.builder.Append(".").Append(node.Method.Name.Substring(4)); + if (node.Arguments.Count > paramFrom) + { + this.builder.Append("["); + AsCommaSeparatedValues(node.Arguments.Skip(paramFrom), ToString); + this.builder.Append("]"); + } } else if (node.Method.IsPropertySetter()) { @@ -1128,4 +1128,4 @@ public static string DisplayName(this Type source, Func getName) // } // } // } -} \ No newline at end of file +} diff --git a/Source/Extensions.cs b/Source/Extensions.cs index e388628a4..588edcbf3 100644 --- a/Source/Extensions.cs +++ b/Source/Extensions.cs @@ -91,10 +91,10 @@ public static string GetValue(object value) { return "\"" + typedValue + "\""; } - if (value is IEnumerable) - { - return "[" + string.Join(", ", ((IEnumerable) value).OfType().Select(GetValue)) + "]"; - } + if (value is IEnumerable) + { + return "[" + string.Join(", ", ((IEnumerable) value).OfType().Select(GetValue)) + "]"; + } return value.ToString(); } diff --git a/Source/GlobalSuppressions.cs b/Source/GlobalSuppressions.cs index d227fc948..c22e7e75f 100644 --- a/Source/GlobalSuppressions.cs +++ b/Source/GlobalSuppressions.cs @@ -18,4 +18,4 @@ [assembly: SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Moq", Scope = "namespace", Target = "Moq.Language")] [assembly: SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Moq", Scope = "namespace", Target = "Moq.Language.Flow")] [assembly: SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Moq", Scope = "namespace", Target = "Moq.Protected")] -[assembly: SuppressMessage("Microsoft.Naming", "CA1716:IdentifiersShouldNotMatchKeywords", MessageId = "Protected", Scope = "namespace", Target = "Moq.Protected")] \ No newline at end of file +[assembly: SuppressMessage("Microsoft.Naming", "CA1716:IdentifiersShouldNotMatchKeywords", MessageId = "Protected", Scope = "namespace", Target = "Moq.Protected")] diff --git a/Source/Guard.cs b/Source/Guard.cs index d0ac0fb89..e5d289fd9 100644 --- a/Source/Guard.cs +++ b/Source/Guard.cs @@ -139,4 +139,4 @@ private static string GetParameterName(LambdaExpression reference) return member.Member.Name; } } -} \ No newline at end of file +} diff --git a/Source/IDefaultValueProvider.cs b/Source/IDefaultValueProvider.cs index 597435525..8c9c87349 100644 --- a/Source/IDefaultValueProvider.cs +++ b/Source/IDefaultValueProvider.cs @@ -53,4 +53,4 @@ internal interface IDefaultValueProvider /// object ProvideDefault(MethodInfo member); } -} \ No newline at end of file +} diff --git a/Source/IDefaultValueProvider.xdoc b/Source/IDefaultValueProvider.xdoc index 7a2d1ee1e..e6536a607 100644 --- a/Source/IDefaultValueProvider.xdoc +++ b/Source/IDefaultValueProvider.xdoc @@ -21,4 +21,4 @@ The member to provide a default value for. - \ No newline at end of file + diff --git a/Source/IInterceptStrategy.cs b/Source/IInterceptStrategy.cs index bd6a42d1a..be1637939 100644 --- a/Source/IInterceptStrategy.cs +++ b/Source/IInterceptStrategy.cs @@ -10,7 +10,7 @@ namespace Moq internal enum InterceptionAction { Continue, - Stop + Stop } internal interface IInterceptStrategy @@ -150,10 +150,10 @@ internal IEnumerable OrderedCalls } #endregion - } + } internal class CurrentInterceptContext - { + { public IProxyCall Call {get; set; } } } diff --git a/Source/IMock.cs b/Source/IMock.cs index 5cabdac18..aee99cc14 100644 --- a/Source/IMock.cs +++ b/Source/IMock.cs @@ -22,4 +22,4 @@ public interface IMock where T : class /// DefaultValue DefaultValue { get; set; } } -} \ No newline at end of file +} diff --git a/Source/IProxyCall.cs b/Source/IProxyCall.cs index 8381a2a6a..6ed479753 100644 --- a/Source/IProxyCall.cs +++ b/Source/IProxyCall.cs @@ -64,4 +64,4 @@ internal interface IProxyCall int FileLine { get; } MethodBase TestMethod { get; } } -} \ No newline at end of file +} diff --git a/Source/Interceptor.cs b/Source/Interceptor.cs index 824fd36eb..3f5cf1325 100644 --- a/Source/Interceptor.cs +++ b/Source/Interceptor.cs @@ -61,7 +61,7 @@ public Interceptor(MockBehavior behavior, Type targetType, Mock mock) InterceptionContext = new InterceptorContext(mock, targetType, behavior); } - internal InterceptorContext InterceptionContext { get; private set; } + internal InterceptorContext InterceptionContext { get; private set; } internal void Verify() { @@ -113,10 +113,10 @@ public void AddCall(IProxyCall call, SetupKind kind) InterceptionContext.AddOrderedCall(call); } - internal void ClearCalls() - { - calls.Clear(); - } + internal void ClearCalls() + { + calls.Clear(); + } private IEnumerable InterceptionStrategies() { @@ -134,10 +134,10 @@ private IEnumerable InterceptionStrategies() [SuppressMessage("Microsoft.Maintainability", "CA1502:AvoidExcessiveComplexity")] public void Intercept(ICallContext invocation) { - CurrentInterceptContext localCtx = new CurrentInterceptContext(); + CurrentInterceptContext localCtx = new CurrentInterceptContext(); foreach (var strategy in InterceptionStrategies()) { - if (InterceptionAction.Stop == strategy.HandleIntercept(invocation, InterceptionContext, localCtx)) + if (InterceptionAction.Stop == strategy.HandleIntercept(invocation, InterceptionContext, localCtx)) { break; } @@ -170,41 +170,41 @@ public override bool Equals(object obj) var eq = key.fixedString == this.fixedString && key.values.Count == this.values.Count; - //the code below is broken as it uses an OR when checking the arguments, this means that if any pair of arguments match - //the result is a match. - //This is only going to hit some edge cases as for the most part the fixed string above spots arguments correctly. - //Fixing this really needs a reworking of the GetHashCode, and also some sorting out of how to compare value types that have been - //boxed correctly (another problem this code has) - var index = 0; - while (eq && index < this.values.Count) - { - eq |= this.values[index] == key.values[index]; - index++; - } - - return eq; + //the code below is broken as it uses an OR when checking the arguments, this means that if any pair of arguments match + //the result is a match. + //This is only going to hit some edge cases as for the most part the fixed string above spots arguments correctly. + //Fixing this really needs a reworking of the GetHashCode, and also some sorting out of how to compare value types that have been + //boxed correctly (another problem this code has) + var index = 0; + while (eq && index < this.values.Count) + { + eq |= this.values[index] == key.values[index]; + index++; + } + + return eq; } - public override int GetHashCode() - { - var hash = fixedString.GetHashCode(); - - var factor = 1; - foreach (var value in values) - { - if (value != null) - { - // we use a factor that increases with each following value (argument) - // so that if the values are in a different order, we get a different hash code - // see GitHub issue #252 - hash ^= value.GetHashCode() / factor; - } - factor *= 3; - } - - return hash; - } - } + public override int GetHashCode() + { + var hash = fixedString.GetHashCode(); + + var factor = 1; + foreach (var value in values) + { + if (value != null) + { + // we use a factor that increases with each following value (argument) + // so that if the values are in a different order, we get a different hash code + // see GitHub issue #252 + hash ^= value.GetHashCode() / factor; + } + factor *= 3; + } + + return hash; + } + } private class ConstantsVisitor : ExpressionVisitor { diff --git a/Source/InterceptorStrategies.cs b/Source/InterceptorStrategies.cs index 1768c3788..09840a96a 100644 --- a/Source/InterceptorStrategies.cs +++ b/Source/InterceptorStrategies.cs @@ -7,131 +7,131 @@ namespace Moq { - internal class HandleMockRecursion : IInterceptStrategy - { + internal class HandleMockRecursion : IInterceptStrategy + { public InterceptionAction HandleIntercept(ICallContext invocation, InterceptorContext ctx, CurrentInterceptContext localctx) - { + { if (invocation.Method != null && invocation.Method.ReturnType != null && - invocation.Method.ReturnType != typeof(void)) - { - Mock recursiveMock; - if (ctx.Mock.InnerMocks.TryGetValue(invocation.Method, out recursiveMock)) - { - invocation.ReturnValue = recursiveMock.Object; - } - else - { - invocation.ReturnValue = ctx.Mock.DefaultValueProvider.ProvideDefault(invocation.Method); - } - return InterceptionAction.Stop; - } - return InterceptionAction.Continue; - } - } - - internal class InvokeBase : IInterceptStrategy - { - public InterceptionAction HandleIntercept(ICallContext invocation, InterceptorContext ctx, CurrentInterceptContext localctx) - { - if (invocation.Method.DeclaringType == typeof(object) || // interface proxy - ctx.Mock.ImplementedInterfaces.Contains(invocation.Method.DeclaringType) && !invocation.Method.IsEventAttach() && !invocation.Method.IsEventDetach() && ctx.Mock.CallBase && !ctx.Mock.MockedType.GetTypeInfo().IsInterface || // class proxy with explicitly implemented interfaces. The method's declaring type is the interface and the method couldn't be abstract - invocation.Method.DeclaringType.GetTypeInfo().IsClass && !invocation.Method.IsAbstract && ctx.Mock.CallBase // class proxy - ) - { - // Invoke underlying implementation. - - // For mocked classes, if the target method was not abstract, - // invoke directly. - // Will only get here for Loose behavior. - // TODO: we may want to provide a way to skip this by the user. - invocation.InvokeBase(); - return InterceptionAction.Stop; - } - else - { - return InterceptionAction.Continue; - } - } - } - - internal class ExecuteCall : IInterceptStrategy - { - InterceptorContext ctx; - public InterceptionAction HandleIntercept(ICallContext invocation, InterceptorContext ctx, CurrentInterceptContext localctx) - { - this.ctx = ctx; - IProxyCall currentCall = localctx.Call; - - if (currentCall != null) - { - currentCall.SetOutParameters(invocation); - - // We first execute, as there may be a Throws - // and therefore we might never get to the - // next line. - currentCall.Execute(invocation); - ThrowIfReturnValueRequired(currentCall, invocation); - return InterceptionAction.Stop; - } - else - { - return InterceptionAction.Continue; - } - } - private void ThrowIfReturnValueRequired(IProxyCall call, ICallContext invocation) - { - if (ctx.Behavior != MockBehavior.Loose && - invocation.Method != null && - invocation.Method.ReturnType != null && - invocation.Method.ReturnType != typeof(void)) - { - var methodCall = call as MethodCallReturn; - if (methodCall == null || !methodCall.HasReturnValue) - { - throw new MockException( - MockException.ExceptionReason.ReturnValueRequired, - ctx.Behavior, - invocation); - } - } - } - } - - internal class ExtractProxyCall : IInterceptStrategy - { - - public InterceptionAction HandleIntercept(ICallContext invocation, InterceptorContext ctx, CurrentInterceptContext localctx) - { - localctx.Call = FluentMockContext.IsActive ? (IProxyCall)null : ctx.OrderedCalls.LastOrDefault(c => c.Matches(invocation)); - if (localctx.Call != null) - { - localctx.Call.EvaluatedSuccessfully(); - } - else if (!FluentMockContext.IsActive && ctx.Behavior == MockBehavior.Strict) - { - throw new MockException(MockException.ExceptionReason.NoSetup, ctx.Behavior, invocation); - } - - return InterceptionAction.Continue; - } - - } - - internal class InterceptMockPropertyMixin : IInterceptStrategy - { - public InterceptionAction HandleIntercept(ICallContext invocation, InterceptorContext ctx, CurrentInterceptContext localctx) - { - var method = invocation.Method; - - if (typeof(IMocked).IsAssignableFrom(method.DeclaringType) && method.Name == "get_Mock") - { - invocation.ReturnValue = ctx.Mock; - return InterceptionAction.Stop; - } - - return InterceptionAction.Continue; - } - } + invocation.Method.ReturnType != typeof(void)) + { + Mock recursiveMock; + if (ctx.Mock.InnerMocks.TryGetValue(invocation.Method, out recursiveMock)) + { + invocation.ReturnValue = recursiveMock.Object; + } + else + { + invocation.ReturnValue = ctx.Mock.DefaultValueProvider.ProvideDefault(invocation.Method); + } + return InterceptionAction.Stop; + } + return InterceptionAction.Continue; + } + } + + internal class InvokeBase : IInterceptStrategy + { + public InterceptionAction HandleIntercept(ICallContext invocation, InterceptorContext ctx, CurrentInterceptContext localctx) + { + if (invocation.Method.DeclaringType == typeof(object) || // interface proxy + ctx.Mock.ImplementedInterfaces.Contains(invocation.Method.DeclaringType) && !invocation.Method.IsEventAttach() && !invocation.Method.IsEventDetach() && ctx.Mock.CallBase && !ctx.Mock.MockedType.GetTypeInfo().IsInterface || // class proxy with explicitly implemented interfaces. The method's declaring type is the interface and the method couldn't be abstract + invocation.Method.DeclaringType.GetTypeInfo().IsClass && !invocation.Method.IsAbstract && ctx.Mock.CallBase // class proxy + ) + { + // Invoke underlying implementation. + + // For mocked classes, if the target method was not abstract, + // invoke directly. + // Will only get here for Loose behavior. + // TODO: we may want to provide a way to skip this by the user. + invocation.InvokeBase(); + return InterceptionAction.Stop; + } + else + { + return InterceptionAction.Continue; + } + } + } + + internal class ExecuteCall : IInterceptStrategy + { + InterceptorContext ctx; + public InterceptionAction HandleIntercept(ICallContext invocation, InterceptorContext ctx, CurrentInterceptContext localctx) + { + this.ctx = ctx; + IProxyCall currentCall = localctx.Call; + + if (currentCall != null) + { + currentCall.SetOutParameters(invocation); + + // We first execute, as there may be a Throws + // and therefore we might never get to the + // next line. + currentCall.Execute(invocation); + ThrowIfReturnValueRequired(currentCall, invocation); + return InterceptionAction.Stop; + } + else + { + return InterceptionAction.Continue; + } + } + private void ThrowIfReturnValueRequired(IProxyCall call, ICallContext invocation) + { + if (ctx.Behavior != MockBehavior.Loose && + invocation.Method != null && + invocation.Method.ReturnType != null && + invocation.Method.ReturnType != typeof(void)) + { + var methodCall = call as MethodCallReturn; + if (methodCall == null || !methodCall.HasReturnValue) + { + throw new MockException( + MockException.ExceptionReason.ReturnValueRequired, + ctx.Behavior, + invocation); + } + } + } + } + + internal class ExtractProxyCall : IInterceptStrategy + { + + public InterceptionAction HandleIntercept(ICallContext invocation, InterceptorContext ctx, CurrentInterceptContext localctx) + { + localctx.Call = FluentMockContext.IsActive ? (IProxyCall)null : ctx.OrderedCalls.LastOrDefault(c => c.Matches(invocation)); + if (localctx.Call != null) + { + localctx.Call.EvaluatedSuccessfully(); + } + else if (!FluentMockContext.IsActive && ctx.Behavior == MockBehavior.Strict) + { + throw new MockException(MockException.ExceptionReason.NoSetup, ctx.Behavior, invocation); + } + + return InterceptionAction.Continue; + } + + } + + internal class InterceptMockPropertyMixin : IInterceptStrategy + { + public InterceptionAction HandleIntercept(ICallContext invocation, InterceptorContext ctx, CurrentInterceptContext localctx) + { + var method = invocation.Method; + + if (typeof(IMocked).IsAssignableFrom(method.DeclaringType) && method.Name == "get_Mock") + { + invocation.ReturnValue = ctx.Mock; + return InterceptionAction.Stop; + } + + return InterceptionAction.Continue; + } + } /// /// Intercept strategy that handles `System.Object` methods. @@ -177,30 +177,30 @@ protected bool IsObjectMethod(MethodInfo method, string name) } } - internal class HandleTracking : IInterceptStrategy - { - - public InterceptionAction HandleIntercept(ICallContext invocation, InterceptorContext ctx, CurrentInterceptContext localctx) - { - // Track current invocation if we're in "record" mode in a fluent invocation context. - if (FluentMockContext.IsActive) - { - FluentMockContext.Current.Add(ctx.Mock, invocation); - } - return InterceptionAction.Continue; - } - } - - internal class HandleDestructor : IInterceptStrategy - { - public InterceptionAction HandleIntercept(ICallContext invocation, InterceptorContext ctx, CurrentInterceptContext localctx) - { - return invocation.Method.IsDestructor() ? InterceptionAction.Stop : InterceptionAction.Continue; - } - } - - internal class AddActualInvocation : IInterceptStrategy - { + internal class HandleTracking : IInterceptStrategy + { + + public InterceptionAction HandleIntercept(ICallContext invocation, InterceptorContext ctx, CurrentInterceptContext localctx) + { + // Track current invocation if we're in "record" mode in a fluent invocation context. + if (FluentMockContext.IsActive) + { + FluentMockContext.Current.Add(ctx.Mock, invocation); + } + return InterceptionAction.Continue; + } + } + + internal class HandleDestructor : IInterceptStrategy + { + public InterceptionAction HandleIntercept(ICallContext invocation, InterceptorContext ctx, CurrentInterceptContext localctx) + { + return invocation.Method.IsDestructor() ? InterceptionAction.Stop : InterceptionAction.Continue; + } + } + + internal class AddActualInvocation : IInterceptStrategy + { /// /// Get an eventInfo for a given event name. Search type ancestors depth first if necessary. @@ -232,80 +232,80 @@ private EventInfo GetEventFromName(string eventName, BindingFlags bindingAttr) return eventInfo; } - foreach (var implementedType in GetAncestorTypes(currentType)) - { - depthFirstProgress.Enqueue(implementedType); - } - } - - return null; - } - - - /// - /// Given a type return all of its ancestors, both types and interfaces. - /// - /// The type to find immediate ancestors of - private static IEnumerable GetAncestorTypes(Type initialType) - { - var baseType = initialType.GetTypeInfo().BaseType; - if (baseType != null) - { - return new[] { baseType }; - } - - return initialType.GetInterfaces(); - } - InterceptorContext ctx; - public InterceptionAction HandleIntercept(ICallContext invocation, InterceptorContext ctx, CurrentInterceptContext localctx) - { - this.ctx = ctx; - if (!FluentMockContext.IsActive) - { - //Special case for events - if (invocation.Method.IsEventAttach()) - { - var delegateInstance = (Delegate)invocation.Arguments[0]; - // TODO: validate we can get the event? - var eventInfo = this.GetEventFromName(invocation.Method.Name.Substring(4)); - - if (ctx.Mock.CallBase && !eventInfo.DeclaringType.GetTypeInfo().IsInterface) - { - invocation.InvokeBase(); - } - else if (delegateInstance != null) - { - ctx.AddEventHandler(eventInfo, (Delegate)invocation.Arguments[0]); - } - - return InterceptionAction.Stop; - } - else if (invocation.Method.IsEventDetach()) - { - var delegateInstance = (Delegate)invocation.Arguments[0]; - // TODO: validate we can get the event? - var eventInfo = this.GetEventFromName(invocation.Method.Name.Substring(7)); - - if (ctx.Mock.CallBase && !eventInfo.DeclaringType.GetTypeInfo().IsInterface) - { - invocation.InvokeBase(); - } - else if (delegateInstance != null) - { - ctx.RemoveEventHandler(eventInfo, (Delegate)invocation.Arguments[0]); - } - - return InterceptionAction.Stop; - } - - // Save to support Verify[expression] pattern. - // In a fluent invocation context, which is a recorder-like - // mode we use to evaluate delegates by actually running them, - // we don't want to count the invocation, or actually run - // previous setups. - ctx.AddInvocation(invocation); - } - return InterceptionAction.Continue; - } - } + foreach (var implementedType in GetAncestorTypes(currentType)) + { + depthFirstProgress.Enqueue(implementedType); + } + } + + return null; + } + + + /// + /// Given a type return all of its ancestors, both types and interfaces. + /// + /// The type to find immediate ancestors of + private static IEnumerable GetAncestorTypes(Type initialType) + { + var baseType = initialType.GetTypeInfo().BaseType; + if (baseType != null) + { + return new[] { baseType }; + } + + return initialType.GetInterfaces(); + } + InterceptorContext ctx; + public InterceptionAction HandleIntercept(ICallContext invocation, InterceptorContext ctx, CurrentInterceptContext localctx) + { + this.ctx = ctx; + if (!FluentMockContext.IsActive) + { + //Special case for events + if (invocation.Method.IsEventAttach()) + { + var delegateInstance = (Delegate)invocation.Arguments[0]; + // TODO: validate we can get the event? + var eventInfo = this.GetEventFromName(invocation.Method.Name.Substring(4)); + + if (ctx.Mock.CallBase && !eventInfo.DeclaringType.GetTypeInfo().IsInterface) + { + invocation.InvokeBase(); + } + else if (delegateInstance != null) + { + ctx.AddEventHandler(eventInfo, (Delegate)invocation.Arguments[0]); + } + + return InterceptionAction.Stop; + } + else if (invocation.Method.IsEventDetach()) + { + var delegateInstance = (Delegate)invocation.Arguments[0]; + // TODO: validate we can get the event? + var eventInfo = this.GetEventFromName(invocation.Method.Name.Substring(7)); + + if (ctx.Mock.CallBase && !eventInfo.DeclaringType.GetTypeInfo().IsInterface) + { + invocation.InvokeBase(); + } + else if (delegateInstance != null) + { + ctx.RemoveEventHandler(eventInfo, (Delegate)invocation.Arguments[0]); + } + + return InterceptionAction.Stop; + } + + // Save to support Verify[expression] pattern. + // In a fluent invocation context, which is a recorder-like + // mode we use to evaluate delegates by actually running them, + // we don't want to count the invocation, or actually run + // previous setups. + ctx.AddInvocation(invocation); + } + return InterceptionAction.Continue; + } + } } diff --git a/Source/It.cs b/Source/It.cs index 920c93a1e..f87abc968 100644 --- a/Source/It.cs +++ b/Source/It.cs @@ -98,29 +98,29 @@ public static TValue IsInRange(TValue from, TValue to, Range rangeKind) () => It.IsInRange(from, to, rangeKind)); } - /// - public static TValue IsIn(IEnumerable items) - { - return Match.Create(value => items.Contains(value), () => It.IsIn(items)); - } - - /// - public static TValue IsIn(params TValue[] items) - { - return Match.Create(value => items.Contains(value), () => It.IsIn(items)); - } - - /// - public static TValue IsNotIn(IEnumerable items) - { - return Match.Create(value => !items.Contains(value), () => It.IsNotIn(items)); - } - - /// - public static TValue IsNotIn(params TValue[] items) - { - return Match.Create(value => !items.Contains(value), () => It.IsNotIn(items)); - } + /// + public static TValue IsIn(IEnumerable items) + { + return Match.Create(value => items.Contains(value), () => It.IsIn(items)); + } + + /// + public static TValue IsIn(params TValue[] items) + { + return Match.Create(value => items.Contains(value), () => It.IsIn(items)); + } + + /// + public static TValue IsNotIn(IEnumerable items) + { + return Match.Create(value => !items.Contains(value), () => It.IsNotIn(items)); + } + + /// + public static TValue IsNotIn(params TValue[] items) + { + return Match.Create(value => !items.Contains(value), () => It.IsNotIn(items)); + } /// public static string IsRegex(string regex) diff --git a/Source/It.xdoc b/Source/It.xdoc index c62661ad5..6beb5ab9d 100644 --- a/Source/It.xdoc +++ b/Source/It.xdoc @@ -28,12 +28,12 @@ Type of the value. - - - Matches any value of the given type, except null. - - Type of the value. - + + + Matches any value of the given type, except null. + + Type of the value. + Matches any value that satisfies the given predicate. @@ -116,7 +116,7 @@ - + Matches any value that is not found in the sequence specified. diff --git a/Source/Language/Flow/IThrowsResult.cs b/Source/Language/Flow/IThrowsResult.cs index ee1c93573..baebc5fc0 100644 --- a/Source/Language/Flow/IThrowsResult.cs +++ b/Source/Language/Flow/IThrowsResult.cs @@ -49,4 +49,4 @@ namespace Moq.Language.Flow public interface IThrowsResult : IOccurrence, IVerifies, IFluentInterface { } -} \ No newline at end of file +} diff --git a/Source/Language/IRaise.cs b/Source/Language/IRaise.cs index 48c52546e..f7e3e6ed2 100644 --- a/Source/Language/IRaise.cs +++ b/Source/Language/IRaise.cs @@ -84,4 +84,4 @@ public partial interface IRaise : IFluentInterface /// The arguments to pass to the custom delegate (non EventHandler-compatible). IVerifies Raises(Action eventExpression, params object[] args); } -} \ No newline at end of file +} diff --git a/Source/Language/IReturns.cs b/Source/Language/IReturns.cs index 49f584386..3edcfa5c7 100644 --- a/Source/Language/IReturns.cs +++ b/Source/Language/IReturns.cs @@ -110,4 +110,4 @@ public partial interface IReturns : IFluentInterface /// The value calculated by the real method of the object. IReturnsResult CallBase(); } -} \ No newline at end of file +} diff --git a/Source/Language/ISetupConditionResult.cs b/Source/Language/ISetupConditionResult.cs index c3f7c33de..e00750596 100644 --- a/Source/Language/ISetupConditionResult.cs +++ b/Source/Language/ISetupConditionResult.cs @@ -53,4 +53,4 @@ public interface ISetupConditionResult where T : class /// ISetup SetupSet(Action setterExpression); } -} \ No newline at end of file +} diff --git a/Source/Language/ISetupSequentialResult.cs b/Source/Language/ISetupSequentialResult.cs index 5540726f4..d4c7bf8da 100644 --- a/Source/Language/ISetupSequentialResult.cs +++ b/Source/Language/ISetupSequentialResult.cs @@ -32,4 +32,4 @@ public interface ISetupSequentialResult /// ISetupSequentialResult CallBase(); } -} \ No newline at end of file +} diff --git a/Source/Language/IThrows.cs b/Source/Language/IThrows.cs index 28cbf44fa..2ac9da020 100644 --- a/Source/Language/IThrows.cs +++ b/Source/Language/IThrows.cs @@ -80,4 +80,4 @@ public interface IThrows : IFluentInterface [SuppressMessage("Microsoft.Design", "CA1004:GenericMethodsShouldProvideTypeParameter")] IThrowsResult Throws() where TException : Exception, new(); } -} \ No newline at end of file +} diff --git a/Source/Linq/FluentMockVisitor.cs b/Source/Linq/FluentMockVisitor.cs index d6d69b266..72290a243 100644 --- a/Source/Linq/FluentMockVisitor.cs +++ b/Source/Linq/FluentMockVisitor.cs @@ -196,4 +196,4 @@ private static MethodInfo GetSetupMethod(Type objectType, Type returnType) .MakeGenericMethod(returnType); } } -} \ No newline at end of file +} diff --git a/Source/Linq/MockQuery.cs b/Source/Linq/MockQuery.cs index 9129b40a7..8a7bb4e1f 100644 --- a/Source/Linq/MockQuery.cs +++ b/Source/Linq/MockQuery.cs @@ -132,4 +132,4 @@ public override string ToString() return this.Expression.ToString(); } } -} \ No newline at end of file +} diff --git a/Source/Linq/Mocks.cs b/Source/Linq/Mocks.cs index 67ffa8238..7ecca6f9e 100644 --- a/Source/Linq/Mocks.cs +++ b/Source/Linq/Mocks.cs @@ -213,4 +213,4 @@ internal static class QueryableMockExtensions return (Mock)fluentMock; } } -} \ No newline at end of file +} diff --git a/Source/Match.cs b/Source/Match.cs index 8fd4e536d..7b2cb5c6b 100644 --- a/Source/Match.cs +++ b/Source/Match.cs @@ -75,11 +75,11 @@ public static T Create(Predicate condition, Expression> renderExpr return Create(new Match(condition, renderExpression)); } - internal static T Create(Match match) - { - SetLastMatch(match); - return default(T); - } + internal static T Create(Match match) + { + SetLastMatch(match); + return default(T); + } /// /// This method is used to set an expression as the last matcher invoked, @@ -102,7 +102,7 @@ private static Match SetLastMatch(Match match) return match; } - } + } /// public class Match : Match diff --git a/Source/Match.xdoc b/Source/Match.xdoc index 698d1f859..3dea61702 100644 --- a/Source/Match.xdoc +++ b/Source/Match.xdoc @@ -91,4 +91,5 @@ - \ No newline at end of file + + diff --git a/Source/MatchExpression.cs b/Source/MatchExpression.cs index 8102e75c3..064c977b1 100644 --- a/Source/MatchExpression.cs +++ b/Source/MatchExpression.cs @@ -67,4 +67,4 @@ public override Type Type public Match Match { get; private set; } } -} \ No newline at end of file +} diff --git a/Source/Matchers/ConstantMatcher.cs b/Source/Matchers/ConstantMatcher.cs index 27d227aa1..b29359893 100644 --- a/Source/Matchers/ConstantMatcher.cs +++ b/Source/Matchers/ConstantMatcher.cs @@ -83,4 +83,4 @@ private bool MatchesEnumerable(object value) return constValues.Cast().SequenceEqual(values.Cast()); } } -} \ No newline at end of file +} diff --git a/Source/Matchers/ExpressionMatcher.cs b/Source/Matchers/ExpressionMatcher.cs index b68fd3cf7..bb8e1bd89 100644 --- a/Source/Matchers/ExpressionMatcher.cs +++ b/Source/Matchers/ExpressionMatcher.cs @@ -62,4 +62,4 @@ public bool Matches(object value) && ExpressionComparer.Default.Equals(this.expression, valueExpression); } } -} \ No newline at end of file +} diff --git a/Source/Matchers/LazyEvalMatcher.cs b/Source/Matchers/LazyEvalMatcher.cs index e3881f26b..82a598f17 100644 --- a/Source/Matchers/LazyEvalMatcher.cs +++ b/Source/Matchers/LazyEvalMatcher.cs @@ -63,4 +63,4 @@ public bool Matches(object value) return false; } } -} \ No newline at end of file +} diff --git a/Source/Matchers/Matcher.cs b/Source/Matchers/Matcher.cs index a7d18f028..041a4a7fd 100644 --- a/Source/Matchers/Matcher.cs +++ b/Source/Matchers/Matcher.cs @@ -60,4 +60,4 @@ public bool Matches(object value) return match.Matches(value); } } -} \ No newline at end of file +} diff --git a/Source/Matchers/MatcherAttributeMatcher.cs b/Source/Matchers/MatcherAttributeMatcher.cs index b119b9873..fdd7dd96e 100644 --- a/Source/Matchers/MatcherAttributeMatcher.cs +++ b/Source/Matchers/MatcherAttributeMatcher.cs @@ -129,4 +129,4 @@ public bool Matches(object value) return (bool)validatorMethod.Invoke(instance, args); } } -} \ No newline at end of file +} diff --git a/Source/Matchers/ParamArrayMatcher.cs b/Source/Matchers/ParamArrayMatcher.cs index c29d5a72d..07f8a1f41 100644 --- a/Source/Matchers/ParamArrayMatcher.cs +++ b/Source/Matchers/ParamArrayMatcher.cs @@ -93,4 +93,4 @@ private void Initialize() } } } -} \ No newline at end of file +} diff --git a/Source/MemberInfoExtensions.cs b/Source/MemberInfoExtensions.cs index 834a7ba62..34ec23b7e 100644 --- a/Source/MemberInfoExtensions.cs +++ b/Source/MemberInfoExtensions.cs @@ -106,4 +106,4 @@ private static string GetGenericArguments(IEnumerable types, Func"; } } -} \ No newline at end of file +} diff --git a/Source/MethodCallReturn.cs b/Source/MethodCallReturn.cs index 66f7204d7..a8dab3a28 100644 --- a/Source/MethodCallReturn.cs +++ b/Source/MethodCallReturn.cs @@ -173,4 +173,4 @@ public override void Execute(ICallContext call) afterReturnCallback(call.Arguments); } } -} \ No newline at end of file +} diff --git a/Source/Mock.cs b/Source/Mock.cs index 827d0d65a..c3cebc1a1 100644 --- a/Source/Mock.cs +++ b/Source/Mock.cs @@ -124,21 +124,21 @@ protected Mock() /// public static void Verify(params Mock[] mocks) - { - foreach (var mock in mocks) - { - mock.Verify(); - } - } + { + foreach (var mock in mocks) + { + mock.Verify(); + } + } /// public static void VerifyAll(params Mock[] mocks) - { - foreach (var mock in mocks) - { - mock.VerifyAll(); - } - } + { + foreach (var mock in mocks) + { + mock.VerifyAll(); + } + } /// public virtual MockBehavior Behavior { get; internal set; } @@ -197,23 +197,23 @@ private object GetObject() /// internal abstract MethodInfo DelegateInterfaceMethod { get; } - /// - /// Allows to check whether expression conversion to the - /// must be performed on the mock, without causing unnecessarily early initialization of - /// the mock instance, which breaks As{T}. - /// - internal abstract bool IsDelegateMock { get; } - - /// - /// Specifies the class that will determine the default - /// value to return when invocations are made that - /// have no setups and need to return a default - /// value (for loose mocks). - /// - internal IDefaultValueProvider DefaultValueProvider - { - get { return this.defaultValueProvider; } - } + /// + /// Allows to check whether expression conversion to the + /// must be performed on the mock, without causing unnecessarily early initialization of + /// the mock instance, which breaks As{T}. + /// + internal abstract bool IsDelegateMock { get; } + + /// + /// Specifies the class that will determine the default + /// value to return when invocations are made that + /// have no setups and need to return a default + /// value (for loose mocks). + /// + internal IDefaultValueProvider DefaultValueProvider + { + get { return this.defaultValueProvider; } + } /// /// Exposes the list of extra interfaces implemented by the mock. @@ -373,14 +373,14 @@ private static bool AreSameMethod(Expression left, Expression right) Expression expression, Times times) { - // .Where does an enumeration, and calls to a mocked method concurrent to VerifyCalls might change the content of ActualCalls. therefore, it is necessary to take a snapshot, using ToList(), so that concurrent calls will not impact the ongoing verification. - var actualCalls = targetInterceptor.InterceptionContext.ActualInvocations.ToList(); + // .Where does an enumeration, and calls to a mocked method concurrent to VerifyCalls might change the content of ActualCalls. therefore, it is necessary to take a snapshot, using ToList(), so that concurrent calls will not impact the ongoing verification. + var actualCalls = targetInterceptor.InterceptionContext.ActualInvocations.ToList(); - var callCount = actualCalls.Where(ac => expected.Matches(ac)).Count(); - if (!times.Verify(callCount)) - { + var callCount = actualCalls.Where(ac => expected.Matches(ac)).Count(); + if (!times.Verify(callCount)) + { var setups = targetInterceptor.InterceptionContext.OrderedCalls.Where(oc => AreSameMethod(oc.SetupExpression, expression)); - ThrowVerifyException(expected, setups, actualCalls, expression, times, callCount); + ThrowVerifyException(expected, setups, actualCalls, expression, times, callCount); } } @@ -439,14 +439,14 @@ private static string FormatInvocations(IEnumerable invocations) #region Setup - internal static MethodCall Setup(Mock mock, Expression> expression, Condition condition) - where T : class - { - return PexProtector.Invoke(() => - { - var methodCall = expression.GetCallInfo(mock); - var method = methodCall.Method; - var args = methodCall.Arguments.ToArray(); + internal static MethodCall Setup(Mock mock, Expression> expression, Condition condition) + where T : class + { + return PexProtector.Invoke(() => + { + var methodCall = expression.GetCallInfo(mock); + var method = methodCall.Method; + var args = methodCall.Arguments.ToArray(); ThrowIfNotMember(expression, method); ThrowIfCantOverride(expression, method); @@ -460,18 +460,18 @@ internal static MethodCall Setup(Mock mock, Expression> expre }); } - internal static MethodCallReturn Setup( - Mock mock, - Expression> expression, - Condition condition) - where T : class - { - return PexProtector.Invoke(() => - { - if (expression.IsProperty()) - { - return SetupGet(mock, expression, condition); - } + internal static MethodCallReturn Setup( + Mock mock, + Expression> expression, + Condition condition) + where T : class + { + return PexProtector.Invoke(() => + { + if (expression.IsProperty()) + { + return SetupGet(mock, expression, condition); + } var methodCall = expression.GetCallInfo(mock); var method = methodCall.Method; @@ -489,19 +489,19 @@ internal static MethodCall Setup(Mock mock, Expression> expre }); } - internal static MethodCallReturn SetupGet( - Mock mock, - Expression> expression, - Condition condition) - where T : class - { - return PexProtector.Invoke(() => - { - if (expression.IsPropertyIndexer()) - { - // Treat indexers as regular method invocations. - return Setup(mock, expression, condition); - } + internal static MethodCallReturn SetupGet( + Mock mock, + Expression> expression, + Condition condition) + where T : class + { + return PexProtector.Invoke(() => + { + if (expression.IsPropertyIndexer()) + { + // Treat indexers as regular method invocations. + return Setup(mock, expression, condition); + } var prop = expression.ToPropertyInfo(); ThrowIfPropertyNotReadable(prop); @@ -519,42 +519,42 @@ internal static MethodCall Setup(Mock mock, Expression> expre }); } - internal static SetterMethodCall SetupSet( - Mock mock, - Action setterExpression, - Condition condition) - where T : class - { - return PexProtector.Invoke(() => - { - return SetupSetImpl>( - mock, - setterExpression, - (m, expr, method, value) => - { - var call = new SetterMethodCall(m, condition, expr, method, value[0]); - m.Interceptor.AddCall(call, SetupKind.PropertySet); - return call; - }); - }); - } - - internal static MethodCall SetupSet(Mock mock, Action setterExpression, Condition condition) - where T : class - { - return PexProtector.Invoke(() => - { - return SetupSetImpl>( - mock, - setterExpression, - (m, expr, method, values) => - { - var call = new MethodCall(m, condition, expr, method, values); - m.Interceptor.AddCall(call, SetupKind.PropertySet); - return call; - }); - }); - } + internal static SetterMethodCall SetupSet( + Mock mock, + Action setterExpression, + Condition condition) + where T : class + { + return PexProtector.Invoke(() => + { + return SetupSetImpl>( + mock, + setterExpression, + (m, expr, method, value) => + { + var call = new SetterMethodCall(m, condition, expr, method, value[0]); + m.Interceptor.AddCall(call, SetupKind.PropertySet); + return call; + }); + }); + } + + internal static MethodCall SetupSet(Mock mock, Action setterExpression, Condition condition) + where T : class + { + return PexProtector.Invoke(() => + { + return SetupSetImpl>( + mock, + setterExpression, + (m, expr, method, values) => + { + var call = new MethodCall(m, condition, expr, method, values); + m.Interceptor.AddCall(call, SetupKind.PropertySet); + return call; + }); + }); + } internal static SetterMethodCall SetupSet( Mock mock, @@ -607,7 +607,7 @@ internal static MethodCall SetupSet(Mock mock, Action setterExpressi // because of delegate currying, look at the last parameter for the Action's backing method, not the first var setterExpressionParameters = setterExpression.GetMethodInfo().GetParameters(); var parameterName = setterExpressionParameters[setterExpressionParameters.Length - 1].Name; - var x = Expression.Parameter(last.Invocation.Method.DeclaringType, parameterName); + var x = Expression.Parameter(last.Invocation.Method.DeclaringType, parameterName); var arguments = last.Invocation.Arguments; var parameters = setter.GetParameters(); @@ -694,15 +694,15 @@ private static void SetupAllProperties(Mock mock, Stack mockedTypesStack) var properties = mockType.GetProperties() .Concat(mockType.GetInterfaces().SelectMany(i => i.GetProperties())) .Where(p => - p.CanRead && p.CanOverrideGet() && - p.GetIndexParameters().Length == 0 && - !(p.CanWrite ^ (p.CanWrite & p.CanOverrideSet()))) + p.CanRead && p.CanOverrideGet() && + p.GetIndexParameters().Length == 0 && + !(p.CanWrite ^ (p.CanWrite & p.CanOverrideSet()))) .Distinct(); - var setupPropertyMethod = mock.GetType().GetMethods() - .First(m => m.Name == "SetupProperty" && m.GetParameters().Length == 2); - var setupGetMethod = mock.GetType().GetMethods() - .First(m => m.Name == "SetupGet" && m.GetParameters().Length == 1); + var setupPropertyMethod = mock.GetType().GetMethods() + .First(m => m.Name == "SetupProperty" && m.GetParameters().Length == 2); + var setupGetMethod = mock.GetType().GetMethods() + .First(m => m.Name == "SetupGet" && m.GetParameters().Length == 1); foreach (var property in properties) { @@ -715,23 +715,23 @@ private static void SetupAllProperties(Mock mock, Stack mockedTypesStack) SetupAllProperties(mocked.Mock, mockedTypesStack); } - if (property.CanWrite) - { - setupPropertyMethod.MakeGenericMethod(property.PropertyType) - .Invoke(mock, new[] { expression, initialValue }); - } - else - { - var genericSetupGetMethod = setupGetMethod.MakeGenericMethod(property.PropertyType); - var returnsMethod = - genericSetupGetMethod - .ReturnType - .GetTypeInfo() - .ImplementedInterfaces - .SingleOrDefault(i => i.Name.Equals("IReturnsGetter`2", StringComparison.OrdinalIgnoreCase)) - .GetTypeInfo() - .DeclaredMethods - .SingleOrDefault(m => m.Name == "Returns" && m.GetParameterTypes().Count() == 1 && m.GetParameterTypes().First() == property.PropertyType); + if (property.CanWrite) + { + setupPropertyMethod.MakeGenericMethod(property.PropertyType) + .Invoke(mock, new[] { expression, initialValue }); + } + else + { + var genericSetupGetMethod = setupGetMethod.MakeGenericMethod(property.PropertyType); + var returnsMethod = + genericSetupGetMethod + .ReturnType + .GetTypeInfo() + .ImplementedInterfaces + .SingleOrDefault(i => i.Name.Equals("IReturnsGetter`2", StringComparison.OrdinalIgnoreCase)) + .GetTypeInfo() + .DeclaredMethods + .SingleOrDefault(m => m.Name == "Returns" && m.GetParameterTypes().Count() == 1 && m.GetParameterTypes().First() == property.PropertyType); var returnsGetter = genericSetupGetMethod.Invoke(mock, new[] {expression}); returnsMethod.Invoke(returnsGetter, new[] {initialValue}); @@ -980,14 +980,14 @@ internal void DoRaise(EventInfo ev, EventArgs args) throw new InvalidOperationException(Resources.RaisedUnassociatedEvent); } - foreach (var del in this.Interceptor.InterceptionContext.GetInvocationList(ev).ToArray()) - { - del.InvokePreserveStack(this.Object, args); - } - } + foreach (var del in this.Interceptor.InterceptionContext.GetInvocationList(ev).ToArray()) + { + del.InvokePreserveStack(this.Object, args); + } + } /// - /// Raises the associated event with the given + /// Raises the associated event with the given /// event argument data. /// internal void DoRaise(EventInfo ev, params object[] args) @@ -998,12 +998,12 @@ internal void DoRaise(EventInfo ev, params object[] args) } foreach (var del in this.Interceptor.InterceptionContext.GetInvocationList(ev).ToArray()) - { - // Non EventHandler-compatible delegates get the straight - // arguments, not the typical "sender, args" arguments. - del.InvokePreserveStack(args); - } - } + { + // Non EventHandler-compatible delegates get the straight + // arguments, not the typical "sender, args" arguments. + del.InvokePreserveStack(args); + } + } #endregion diff --git a/Source/MockBehavior.cs b/Source/MockBehavior.cs index 98f89cd86..48aa7c438 100644 --- a/Source/MockBehavior.cs +++ b/Source/MockBehavior.cs @@ -38,7 +38,6 @@ //[This is the BSD license, see // http://www.opensource.org/licenses/bsd-license.php] - namespace Moq { /// diff --git a/Source/MockDefaultValueProvider.cs b/Source/MockDefaultValueProvider.cs index f73a6bb2f..eed1e4080 100644 --- a/Source/MockDefaultValueProvider.cs +++ b/Source/MockDefaultValueProvider.cs @@ -64,18 +64,18 @@ public override object ProvideDefault(MethodInfo member) Mock mock = null; if (value == null && member.ReturnType.IsMockeable()) { - mock = owner.InnerMocks.GetOrAdd(member, info => - { - // Create a new mock to be placed to InnerMocks dictionary if it's missing there - var mockType = typeof(Mock<>).MakeGenericType(info.ReturnType); - Mock newMock = (Mock)Activator.CreateInstance(mockType, owner.Behavior); - newMock.DefaultValue = owner.DefaultValue; - newMock.CallBase = owner.CallBase; - return newMock; - }); + mock = owner.InnerMocks.GetOrAdd(member, info => + { + // Create a new mock to be placed to InnerMocks dictionary if it's missing there + var mockType = typeof(Mock<>).MakeGenericType(info.ReturnType); + Mock newMock = (Mock)Activator.CreateInstance(mockType, owner.Behavior); + newMock.DefaultValue = owner.DefaultValue; + newMock.CallBase = owner.CallBase; + return newMock; + }); } return mock != null ? mock.Object : value; } } -} \ No newline at end of file +} diff --git a/Source/MockException.cs b/Source/MockException.cs index 6e8169f5f..10928d9ef 100644 --- a/Source/MockException.cs +++ b/Source/MockException.cs @@ -116,13 +116,13 @@ internal ExceptionReason Reason get { return reason; } } - /// - /// Indicates whether this exception is a verification fault raised by Verify() - /// - public bool IsVerificationError - { - get { return reason == ExceptionReason.VerificationFailed; } - } + /// + /// Indicates whether this exception is a verification fault raised by Verify() + /// + public bool IsVerificationError + { + get { return reason == ExceptionReason.VerificationFailed; } + } private static string GetMessage( MockBehavior behavior, @@ -199,26 +199,26 @@ private static string GetRawSetups(IProxyCall[] failedSetups) //var message = new StringBuilder(); //foreach (var setup in failedSetups) //{ - // if (setup.FailMessage != null) - // { - // message.Append(setup.FailMessage).Append(": "); - // } - - // var lambda = setup.SetupExpression.PartialMatcherAwareEval().ToLambda(); - // var targetTypeName = lambda.Parameters[0].Type.Name; - - // message.Append(targetTypeName).Append(" ").Append(lambda.ToStringFixed()); - - // if (setup.TestMethod != null) - // { - // message.AppendFormat( - // " ({0}() in {1}: line {2})", - // setup.TestMethod.Name, - // setup.FileName, - // setup.FileLine); - // } - - // message.AppendLine(); + // if (setup.FailMessage != null) + // { + // message.Append(setup.FailMessage).Append(": "); + // } + + // var lambda = setup.SetupExpression.PartialMatcherAwareEval().ToLambda(); + // var targetTypeName = lambda.Parameters[0].Type.Name; + + // message.Append(targetTypeName).Append(" ").Append(lambda.ToStringFixed()); + + // if (setup.TestMethod != null) + // { + // message.AppendFormat( + // " ({0}() in {1}: line {2})", + // setup.TestMethod.Name, + // setup.FileName, + // setup.FileLine); + // } + + // message.AppendLine(); //} //return message.ToString(); @@ -241,4 +241,4 @@ internal string GetRawSetups() } #endif } -} \ No newline at end of file +} diff --git a/Source/MockExtensions.cs b/Source/MockExtensions.cs index f47230723..ba22a45f2 100644 --- a/Source/MockExtensions.cs +++ b/Source/MockExtensions.cs @@ -8,35 +8,35 @@ namespace Moq { - using Moq.Proxy; + using Moq.Proxy; - /// - /// Provides additional methods on mocks. - /// - /// - /// Those methods are useful for Testeroids support. - /// - public static class MockExtensions - { - /// - /// Resets the calls previously made on the specified mock. - /// - /// The mock whose calls need to be reset. - public static void ResetCalls(this Mock mock) - { - mock.Interceptor.InterceptionContext.ClearInvocations(); - } + /// + /// Provides additional methods on mocks. + /// + /// + /// Those methods are useful for Testeroids support. + /// + public static class MockExtensions + { + /// + /// Resets the calls previously made on the specified mock. + /// + /// The mock whose calls need to be reset. + public static void ResetCalls(this Mock mock) + { + mock.Interceptor.InterceptionContext.ClearInvocations(); + } - /// - /// Resets mock state, including setups and any previously made calls. - /// - /// The mock that needs to be reset. - public static void Reset(this Mock mock) - { - mock.Interceptor.InterceptionContext.ClearOrderedCalls(); - mock.Interceptor.InterceptionContext.ClearEventHandlers(); - mock.Interceptor.ClearCalls(); - mock.ResetCalls(); - } - } + /// + /// Resets mock state, including setups and any previously made calls. + /// + /// The mock that needs to be reset. + public static void Reset(this Mock mock) + { + mock.Interceptor.InterceptionContext.ClearOrderedCalls(); + mock.Interceptor.InterceptionContext.ClearEventHandlers(); + mock.Interceptor.ClearCalls(); + mock.ResetCalls(); + } + } } diff --git a/Source/MockRepository.cs b/Source/MockRepository.cs index aa8ea63ce..7ee64e600 100644 --- a/Source/MockRepository.cs +++ b/Source/MockRepository.cs @@ -148,4 +148,4 @@ public MockRepository(MockBehavior defaultBehavior) } #pragma warning restore 618 } -} \ No newline at end of file +} diff --git a/Source/MockSequence.cs b/Source/MockSequence.cs index 0a0cfee6e..2fabfbb44 100644 --- a/Source/MockSequence.cs +++ b/Source/MockSequence.cs @@ -37,8 +37,8 @@ internal ISetupConditionResult For(Mock mock) var expectationPosition = sequenceLength++; return mock.When(new Condition( - condition: () => expectationPosition == sequenceStep, - success: NextStep)); + condition: () => expectationPosition == sequenceStep, + success: NextStep)); } } diff --git a/Source/Moq.NetCore.csproj b/Source/Moq.NetCore.csproj index 0edcfc856..c933d1108 100644 --- a/Source/Moq.NetCore.csproj +++ b/Source/Moq.NetCore.csproj @@ -1,65 +1,65 @@  - - netstandard1.3 - ../Moq.snk - true - true - Moq - Moq - false - + + netstandard1.3 + ../Moq.snk + true + true + Moq + Moq + false + - - true - true - 4 - bin\$(Configuration)\$(AssemblyName).xml - true - 0419 - + + true + true + 4 + bin\$(Configuration)\$(AssemblyName).xml + true + 0419 + - - $(DefineConstants);NETCORE - + + $(DefineConstants);NETCORE + - - - - - - - - - - - + + + + + + + + + + + - - - TextTemplatingFileGenerator - - - TextTemplatingFileGenerator - - - TextTemplatingFileGenerator - - - TextTemplatingFileGenerator - - - TextTemplatingFileGenerator - - - TextTemplatingFileGenerator - - - TextTemplatingFileGenerator - - - TextTemplatingFileGenerator - - + + + TextTemplatingFileGenerator + + + TextTemplatingFileGenerator + + + TextTemplatingFileGenerator + + + TextTemplatingFileGenerator + + + TextTemplatingFileGenerator + + + TextTemplatingFileGenerator + + + TextTemplatingFileGenerator + + + TextTemplatingFileGenerator + + diff --git a/Source/Moq.csproj b/Source/Moq.csproj index a78eb07e8..6d34db107 100644 --- a/Source/Moq.csproj +++ b/Source/Moq.csproj @@ -1,250 +1,250 @@  - - Debug - AnyCPU - 9.0.30729 - 2.0 - {1C91AC30-5977-4BE5-BA67-8EB186C03514} - Library - Properties - Moq - Moq - v4.5 - 512 - true - ..\Moq.snk - - - true - true - bin\$(Configuration)\ - true - full - prompt - 4 - bin\$(Configuration)\$(AssemblyName).xml - true - AllRules.ruleset - 0419 - false - - - $(DefineConstants);TRACE;DEBUG;DESKTOP;FEATURE_SERIALIZATION - - - $(DefineConstants);TRACE;CODE_ANALYSIS;FEATURE_SERIALIZATION - true - - - - - - - - - - - - - - - - True - True - ICallback.tt - - - - True - True - IRaise.tt - - - - True - True - IReturns.tt - - - - - - - - - - - - - - - - True - True - MethodCall.tt - - - True - True - MethodCallReturn.tt - - - True - True - Delegates.tt - - - - - - - - - - - - True - True - ReturnsExtensions.tt - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - True - True - Resources.resx - - - - - - - - - - - ResXFileCodeGenerator - Designer - Resources.Designer.cs - - - - - Moq.snk - - - IDefaultValueProvider.cs - - - It.cs - - - TextTemplatingFileGenerator - ICallback.Generated.cs - - - TextTemplatingFileGenerator - IRaise.Generated.cs - - - TextTemplatingFileGenerator - IReturns.Generated.cs - - - Match.cs - - - TextTemplatingFileGenerator - MethodCallReturn.Generated.cs - - - TextTemplatingFileGenerator - Delegates.cs - - - Mock.Generic.cs - Designer - - - Mock.cs - - - - - - - - - - - - - - - - - - - - - - - - - - TextTemplatingFileGenerator - MethodCall.Generated.cs - - - - Times.cs - - - - - TextTemplatingFileGenerator - ReturnsExtensions.Generated.cs - - - - - - - - - - - \ No newline at end of file + + Debug + AnyCPU + 9.0.30729 + 2.0 + {1C91AC30-5977-4BE5-BA67-8EB186C03514} + Library + Properties + Moq + Moq + v4.5 + 512 + true + ..\Moq.snk + + + true + true + bin\$(Configuration)\ + true + full + prompt + 4 + bin\$(Configuration)\$(AssemblyName).xml + true + AllRules.ruleset + 0419 + false + + + $(DefineConstants);TRACE;DEBUG;DESKTOP;FEATURE_SERIALIZATION + + + $(DefineConstants);TRACE;CODE_ANALYSIS;FEATURE_SERIALIZATION + true + + + + + + + + + + + + + + + + True + True + ICallback.tt + + + + True + True + IRaise.tt + + + + True + True + IReturns.tt + + + + + + + + + + + + + + + + True + True + MethodCall.tt + + + True + True + MethodCallReturn.tt + + + True + True + Delegates.tt + + + + + + + + + + + + True + True + ReturnsExtensions.tt + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + True + True + Resources.resx + + + + + + + + + + + ResXFileCodeGenerator + Designer + Resources.Designer.cs + + + + + Moq.snk + + + IDefaultValueProvider.cs + + + It.cs + + + TextTemplatingFileGenerator + ICallback.Generated.cs + + + TextTemplatingFileGenerator + IRaise.Generated.cs + + + TextTemplatingFileGenerator + IReturns.Generated.cs + + + Match.cs + + + TextTemplatingFileGenerator + MethodCallReturn.Generated.cs + + + TextTemplatingFileGenerator + Delegates.cs + + + Mock.Generic.cs + Designer + + + Mock.cs + + + + + + + + + + + + + + + + + + + + + + + + + + TextTemplatingFileGenerator + MethodCall.Generated.cs + + + + Times.cs + + + + + TextTemplatingFileGenerator + ReturnsExtensions.Generated.cs + + + + + + + + + + + diff --git a/Source/Obsolete/IOccurrence.cs b/Source/Obsolete/IOccurrence.cs index ed454a445..8e877cd91 100644 --- a/Source/Obsolete/IOccurrence.cs +++ b/Source/Obsolete/IOccurrence.cs @@ -77,4 +77,4 @@ public interface IOccurrence : IFluentInterface [EditorBrowsable(EditorBrowsableState.Never)] IVerifies AtMost(int callCount); } -} \ No newline at end of file +} diff --git a/Source/Obsolete/Mock.Generic.Legacy.cs b/Source/Obsolete/Mock.Generic.Legacy.cs index 89a36c046..476ea5bac 100644 --- a/Source/Obsolete/Mock.Generic.Legacy.cs +++ b/Source/Obsolete/Mock.Generic.Legacy.cs @@ -144,4 +144,4 @@ public static class MockLegacyExtensions Mock.VerifySet(mock, expression, value, Times.AtLeastOnce(), failMessage); } } -} \ No newline at end of file +} diff --git a/Source/Obsolete/Mock.Legacy.cs b/Source/Obsolete/Mock.Legacy.cs index 210caae52..a9ec90e3d 100644 --- a/Source/Obsolete/Mock.Legacy.cs +++ b/Source/Obsolete/Mock.Legacy.cs @@ -103,4 +103,4 @@ public partial class Mock VerifyCalls(GetInterceptor(((MemberExpression)expression.Body).Expression, mock), expected, expression, times); } } -} \ No newline at end of file +} diff --git a/Source/Obsolete/MockFactory.cs b/Source/Obsolete/MockFactory.cs index 9631180d6..7c7c43755 100644 --- a/Source/Obsolete/MockFactory.cs +++ b/Source/Obsolete/MockFactory.cs @@ -352,4 +352,4 @@ protected virtual void VerifyMocks(Action verifyAction) } } } -} \ No newline at end of file +} diff --git a/Source/Obsolete/ObsoleteMockExtensions.cs b/Source/Obsolete/ObsoleteMockExtensions.cs index e8f82018e..83c3e8736 100644 --- a/Source/Obsolete/ObsoleteMockExtensions.cs +++ b/Source/Obsolete/ObsoleteMockExtensions.cs @@ -207,4 +207,4 @@ public static class ObsoleteMockExtensions Mock.VerifySet(mock, expression, times, failMessage); } } -} \ No newline at end of file +} diff --git a/Source/ObsoleteMockException.cs b/Source/ObsoleteMockException.cs index f68a97598..9384683e2 100644 --- a/Source/ObsoleteMockException.cs +++ b/Source/ObsoleteMockException.cs @@ -191,26 +191,26 @@ private static string GetRawSetups(IProxyCall[] failedSetups) //var message = new StringBuilder(); //foreach (var setup in failedSetups) //{ - // if (setup.FailMessage != null) - // { - // message.Append(setup.FailMessage).Append(": "); - // } - - // var lambda = setup.SetupExpression.PartialMatcherAwareEval().ToLambda(); - // var targetTypeName = lambda.Parameters[0].Type.Name; - - // message.Append(targetTypeName).Append(" ").Append(lambda.ToStringFixed()); - - // if (setup.TestMethod != null) - // { - // message.AppendFormat( - // " ({0}() in {1}: line {2})", - // setup.TestMethod.Name, - // setup.FileName, - // setup.FileLine); - // } - - // message.AppendLine(); + // if (setup.FailMessage != null) + // { + // message.Append(setup.FailMessage).Append(": "); + // } + + // var lambda = setup.SetupExpression.PartialMatcherAwareEval().ToLambda(); + // var targetTypeName = lambda.Parameters[0].Type.Name; + + // message.Append(targetTypeName).Append(" ").Append(lambda.ToStringFixed()); + + // if (setup.TestMethod != null) + // { + // message.AppendFormat( + // " ({0}() in {1}: line {2})", + // setup.TestMethod.Name, + // setup.FileName, + // setup.FileLine); + // } + + // message.AppendLine(); //} //return message.ToString(); @@ -233,4 +233,4 @@ internal string GetRawSetups() } #endif } -} \ No newline at end of file +} diff --git a/Source/PexProtector.cs b/Source/PexProtector.cs index b5095309c..a66392689 100644 --- a/Source/PexProtector.cs +++ b/Source/PexProtector.cs @@ -61,4 +61,4 @@ public static T Invoke(Func function) return function(); } } -} \ No newline at end of file +} diff --git a/Source/Properties/Resources.Designer.cs b/Source/Properties/Resources.Designer.cs index d81ed698c..a21a24bbd 100644 --- a/Source/Properties/Resources.Designer.cs +++ b/Source/Properties/Resources.Designer.cs @@ -9,587 +9,587 @@ //------------------------------------------------------------------------------ namespace Moq.Properties { - using System; - using System.Reflection; + using System; + using System.Reflection; - /// - /// A strongly-typed resource class, for looking up localized strings, etc. - /// - // This class was auto-generated by the StronglyTypedResourceBuilder - // class via a tool like ResGen or Visual Studio. - // To add or remove a member, edit your .ResX file then rerun ResGen - // with the /str option, or rebuild your VS project. - [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "4.0.0.0")] - [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] - [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] - internal class Resources { - - private static global::System.Resources.ResourceManager resourceMan; - - private static global::System.Globalization.CultureInfo resourceCulture; - - [global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] - internal Resources() { - } - - /// - /// Returns the cached ResourceManager instance used by this class. - /// - [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] - internal static global::System.Resources.ResourceManager ResourceManager { - get { - if (object.ReferenceEquals(resourceMan, null)) { - global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("Moq.Properties.Resources", typeof(Resources).GetTypeInfo().Assembly); - resourceMan = temp; - } - return resourceMan; - } - } - - /// - /// Overrides the current thread's CurrentUICulture property for all - /// resource lookups using this strongly typed resource class. - /// - [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] - internal static global::System.Globalization.CultureInfo Culture { - get { - return resourceCulture; - } - set { - resourceCulture = value; - } - } - - /// - /// Looks up a localized string similar to Mock type has already been initialized by accessing its Object property. Adding interfaces must be done before that.. - /// - internal static string AlreadyInitialized { - get { - return ResourceManager.GetString("AlreadyInitialized", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to Value cannot be an empty string.. - /// - internal static string ArgumentCannotBeEmpty { - get { - return ResourceManager.GetString("ArgumentCannotBeEmpty", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to Can only add interfaces to the mock.. - /// - internal static string AsMustBeInterface { - get { - return ResourceManager.GetString("AsMustBeInterface", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to Can't set return value for void method {0}.. - /// - internal static string CantSetReturnValueForVoid { - get { - return ResourceManager.GetString("CantSetReturnValueForVoid", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to Constructor arguments cannot be passed for delegate mocks.. - /// - internal static string ConstructorArgsForDelegate { - get { - return ResourceManager.GetString("ConstructorArgsForDelegate", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to Constructor arguments cannot be passed for interface mocks.. - /// - internal static string ConstructorArgsForInterface { - get { - return ResourceManager.GetString("ConstructorArgsForInterface", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to A matching constructor for the given arguments was not found on the mocked type.. - /// - internal static string ConstructorNotFound { - get { - return ResourceManager.GetString("ConstructorNotFound", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to Could not locate event for attach or detach method {0}.. - /// - internal static string EventNofFound { - get { - return ResourceManager.GetString("EventNofFound", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to Expression {0} involves a field access, which is not supported. Use properties instead.. - /// - internal static string FieldsNotSupported { - get { - return ResourceManager.GetString("FieldsNotSupported", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to Type to mock must be an interface or an abstract or non-sealed class. . - /// - internal static string InvalidMockClass { - get { - return ResourceManager.GetString("InvalidMockClass", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to Cannot retrieve a mock with the given object type {0} as it's not the main type of the mock or any of its additional interfaces. - ///Please cast the argument to one of the supported types: {1}. - ///Remember that there's no generics covariance in the CLR, so your object must be one of these types in order for the call to succeed.. - /// - internal static string InvalidMockGetType { - get { - return ResourceManager.GetString("InvalidMockGetType", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to The equals ("==" or "=" in VB) and the conditional 'and' ("&&" or "AndAlso" in VB) operators are the only ones supported in the query specification expression. Unsupported expression: {0}. - /// - internal static string LinqBinaryOperatorNotSupported { - get { - return ResourceManager.GetString("LinqBinaryOperatorNotSupported", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to LINQ method '{0}' not supported.. - /// - internal static string LinqMethodNotSupported { - get { - return ResourceManager.GetString("LinqMethodNotSupported", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to Expression contains a call to a method which is not virtual (overridable in VB) or abstract. Unsupported expression: {0}. - /// - internal static string LinqMethodNotVirtual { - get { - return ResourceManager.GetString("LinqMethodNotVirtual", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to Member {0}.{1} does not exist.. - /// - internal static string MemberMissing { - get { - return ResourceManager.GetString("MemberMissing", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to Method {0}.{1} is public. Use strong-typed Expect overload instead: - ///mock.Setup(x => x.{1}()); - ///. - /// - internal static string MethodIsPublic { - get { - return ResourceManager.GetString("MethodIsPublic", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to {0} invocation failed with mock behavior {1}. - ///{2}. - /// - internal static string MockExceptionMessage { - get { - return ResourceManager.GetString("MockExceptionMessage", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to Expected only {0} calls to {1}.. - /// - internal static string MoreThanNCalls { - get { - return ResourceManager.GetString("MoreThanNCalls", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to Expected only one call to {0}.. - /// - internal static string MoreThanOneCall { - get { - return ResourceManager.GetString("MoreThanOneCall", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to {0} - ///Expected invocation on the mock at least {2} times, but was {4} times: {1}. - /// - internal static string NoMatchingCallsAtLeast { - get { - return ResourceManager.GetString("NoMatchingCallsAtLeast", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to {0} - ///Expected invocation on the mock at least once, but was never performed: {1}. - /// - internal static string NoMatchingCallsAtLeastOnce { - get { - return ResourceManager.GetString("NoMatchingCallsAtLeastOnce", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to {0} - ///Expected invocation on the mock at most {3} times, but was {4} times: {1}. - /// - internal static string NoMatchingCallsAtMost { - get { - return ResourceManager.GetString("NoMatchingCallsAtMost", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to {0} - ///Expected invocation on the mock at most once, but was {4} times: {1}. - /// - internal static string NoMatchingCallsAtMostOnce { - get { - return ResourceManager.GetString("NoMatchingCallsAtMostOnce", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to {0} - ///Expected invocation on the mock between {2} and {3} times (Exclusive), but was {4} times: {1}. - /// - internal static string NoMatchingCallsBetweenExclusive { - get { - return ResourceManager.GetString("NoMatchingCallsBetweenExclusive", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to {0} - ///Expected invocation on the mock between {2} and {3} times (Inclusive), but was {4} times: {1}. - /// - internal static string NoMatchingCallsBetweenInclusive { - get { - return ResourceManager.GetString("NoMatchingCallsBetweenInclusive", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to {0} - ///Expected invocation on the mock exactly {2} times, but was {4} times: {1}. - /// - internal static string NoMatchingCallsExactly { - get { - return ResourceManager.GetString("NoMatchingCallsExactly", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to {0} - ///Expected invocation on the mock should never have been performed, but was {4} times: {1}. - /// - internal static string NoMatchingCallsNever { - get { - return ResourceManager.GetString("NoMatchingCallsNever", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to {0} - ///Expected invocation on the mock once, but was {4} times: {1}. - /// - internal static string NoMatchingCallsOnce { - get { - return ResourceManager.GetString("NoMatchingCallsOnce", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to All invocations on the mock must have a corresponding setup.. - /// - internal static string NoSetup { - get { - return ResourceManager.GetString("NoSetup", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to Object instance was not created by Moq.. - /// - internal static string ObjectInstanceNotMock { - get { - return ResourceManager.GetString("ObjectInstanceNotMock", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to Out expression must evaluate to a constant value.. - /// - internal static string OutExpressionMustBeConstantValue { - get { - return ResourceManager.GetString("OutExpressionMustBeConstantValue", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to Property {0}.{1} does not have a getter.. - /// - internal static string PropertyGetNotFound { - get { - return ResourceManager.GetString("PropertyGetNotFound", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to Property {0}.{1} does not exist.. - /// - internal static string PropertyMissing { - get { - return ResourceManager.GetString("PropertyMissing", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to Property {0}.{1} is write-only.. - /// - internal static string PropertyNotReadable { - get { - return ResourceManager.GetString("PropertyNotReadable", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to Property {0}.{1} is read-only.. - /// - internal static string PropertyNotWritable { - get { - return ResourceManager.GetString("PropertyNotWritable", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to Property {0}.{1} does not have a setter.. - /// - internal static string PropertySetNotFound { - get { - return ResourceManager.GetString("PropertySetNotFound", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to Cannot raise a mocked event unless it has been associated (attached) to a concrete event in a mocked object.. - /// - internal static string RaisedUnassociatedEvent { - get { - return ResourceManager.GetString("RaisedUnassociatedEvent", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to Ref expression must evaluate to a constant value.. - /// - internal static string RefExpressionMustBeConstantValue { - get { - return ResourceManager.GetString("RefExpressionMustBeConstantValue", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to Invocation needs to return a value and therefore must have a corresponding setup that provides it.. - /// - internal static string ReturnValueRequired { - get { - return ResourceManager.GetString("ReturnValueRequired", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to A lambda expression is expected as the argument to It.Is<T>.. - /// - internal static string SetupLambda { - get { - return ResourceManager.GetString("SetupLambda", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to Invocation {0} should not have been made.. - /// - internal static string SetupNever { - get { - return ResourceManager.GetString("SetupNever", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to Expression is not a method invocation: {0}. - /// - internal static string SetupNotMethod { - get { - return ResourceManager.GetString("SetupNotMethod", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to Expression is not a property access: {0}. - /// - internal static string SetupNotProperty { - get { - return ResourceManager.GetString("SetupNotProperty", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to Expression is not a property setter invocation.. - /// - internal static string SetupNotSetter { - get { - return ResourceManager.GetString("SetupNotSetter", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to Expression references a method that does not belong to the mocked object: {0}. - /// - internal static string SetupOnNonMemberMethod { - get { - return ResourceManager.GetString("SetupOnNonMemberMethod", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to Invalid setup on a non-virtual (overridable in VB) member: {0}. - /// - internal static string SetupOnNonOverridableMember { - get { - return ResourceManager.GetString("SetupOnNonOverridableMember", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to Type {0} does not implement required interface {1}. - /// - internal static string TypeNotImplementInterface { - get { - return ResourceManager.GetString("TypeNotImplementInterface", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to Type {0} does not from required type {1}. - /// - internal static string TypeNotInheritFromType { - get { - return ResourceManager.GetString("TypeNotInheritFromType", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to To specify a setup for public property {0}.{1}, use the typed overloads, such as: - ///mock.Setup(x => x.{1}).Returns(value); - ///mock.SetupGet(x => x.{1}).Returns(value); //equivalent to previous one - ///mock.SetupSet(x => x.{1}).Callback(callbackDelegate); - ///. - /// - internal static string UnexpectedPublicProperty { - get { - return ResourceManager.GetString("UnexpectedPublicProperty", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to Unsupported expression: {0}. - /// - internal static string UnsupportedExpression { - get { - return ResourceManager.GetString("UnsupportedExpression", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to Only property accesses are supported in intermediate invocations on a setup. Unsupported expression {0}.. - /// - internal static string UnsupportedIntermediateExpression { - get { - return ResourceManager.GetString("UnsupportedIntermediateExpression", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to Expression contains intermediate property access {0}.{1} which is of type {2} and cannot be mocked. Unsupported expression {3}.. - /// - internal static string UnsupportedIntermediateType { - get { - return ResourceManager.GetString("UnsupportedIntermediateType", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to Setter expression cannot use argument matchers that receive parameters.. - /// - internal static string UnsupportedMatcherParamsForSetter { - get { - return ResourceManager.GetString("UnsupportedMatcherParamsForSetter", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to Member {0} is not supported for protected mocking.. - /// - internal static string UnsupportedMember { - get { - return ResourceManager.GetString("UnsupportedMember", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to Setter expression can only use static custom matchers.. - /// - internal static string UnsupportedNonStaticMatcherForSetter { - get { - return ResourceManager.GetString("UnsupportedNonStaticMatcherForSetter", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to The following setups were not matched: - ///{0}. - /// - internal static string VerficationFailed { - get { - return ResourceManager.GetString("VerficationFailed", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to Invalid verify on a non-virtual (overridable in VB) member: {0}. - /// - internal static string VerifyOnNonVirtualMember { - get { - return ResourceManager.GetString("VerifyOnNonVirtualMember", resourceCulture); - } - } - } + /// + /// A strongly-typed resource class, for looking up localized strings, etc. + /// + // This class was auto-generated by the StronglyTypedResourceBuilder + // class via a tool like ResGen or Visual Studio. + // To add or remove a member, edit your .ResX file then rerun ResGen + // with the /str option, or rebuild your VS project. + [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "4.0.0.0")] + [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] + [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] + internal class Resources { + + private static global::System.Resources.ResourceManager resourceMan; + + private static global::System.Globalization.CultureInfo resourceCulture; + + [global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] + internal Resources() { + } + + /// + /// Returns the cached ResourceManager instance used by this class. + /// + [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] + internal static global::System.Resources.ResourceManager ResourceManager { + get { + if (object.ReferenceEquals(resourceMan, null)) { + global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("Moq.Properties.Resources", typeof(Resources).GetTypeInfo().Assembly); + resourceMan = temp; + } + return resourceMan; + } + } + + /// + /// Overrides the current thread's CurrentUICulture property for all + /// resource lookups using this strongly typed resource class. + /// + [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] + internal static global::System.Globalization.CultureInfo Culture { + get { + return resourceCulture; + } + set { + resourceCulture = value; + } + } + + /// + /// Looks up a localized string similar to Mock type has already been initialized by accessing its Object property. Adding interfaces must be done before that.. + /// + internal static string AlreadyInitialized { + get { + return ResourceManager.GetString("AlreadyInitialized", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Value cannot be an empty string.. + /// + internal static string ArgumentCannotBeEmpty { + get { + return ResourceManager.GetString("ArgumentCannotBeEmpty", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Can only add interfaces to the mock.. + /// + internal static string AsMustBeInterface { + get { + return ResourceManager.GetString("AsMustBeInterface", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Can't set return value for void method {0}.. + /// + internal static string CantSetReturnValueForVoid { + get { + return ResourceManager.GetString("CantSetReturnValueForVoid", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Constructor arguments cannot be passed for delegate mocks.. + /// + internal static string ConstructorArgsForDelegate { + get { + return ResourceManager.GetString("ConstructorArgsForDelegate", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Constructor arguments cannot be passed for interface mocks.. + /// + internal static string ConstructorArgsForInterface { + get { + return ResourceManager.GetString("ConstructorArgsForInterface", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to A matching constructor for the given arguments was not found on the mocked type.. + /// + internal static string ConstructorNotFound { + get { + return ResourceManager.GetString("ConstructorNotFound", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Could not locate event for attach or detach method {0}.. + /// + internal static string EventNofFound { + get { + return ResourceManager.GetString("EventNofFound", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Expression {0} involves a field access, which is not supported. Use properties instead.. + /// + internal static string FieldsNotSupported { + get { + return ResourceManager.GetString("FieldsNotSupported", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Type to mock must be an interface or an abstract or non-sealed class. . + /// + internal static string InvalidMockClass { + get { + return ResourceManager.GetString("InvalidMockClass", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Cannot retrieve a mock with the given object type {0} as it's not the main type of the mock or any of its additional interfaces. + ///Please cast the argument to one of the supported types: {1}. + ///Remember that there's no generics covariance in the CLR, so your object must be one of these types in order for the call to succeed.. + /// + internal static string InvalidMockGetType { + get { + return ResourceManager.GetString("InvalidMockGetType", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to The equals ("==" or "=" in VB) and the conditional 'and' ("&&" or "AndAlso" in VB) operators are the only ones supported in the query specification expression. Unsupported expression: {0}. + /// + internal static string LinqBinaryOperatorNotSupported { + get { + return ResourceManager.GetString("LinqBinaryOperatorNotSupported", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to LINQ method '{0}' not supported.. + /// + internal static string LinqMethodNotSupported { + get { + return ResourceManager.GetString("LinqMethodNotSupported", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Expression contains a call to a method which is not virtual (overridable in VB) or abstract. Unsupported expression: {0}. + /// + internal static string LinqMethodNotVirtual { + get { + return ResourceManager.GetString("LinqMethodNotVirtual", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Member {0}.{1} does not exist.. + /// + internal static string MemberMissing { + get { + return ResourceManager.GetString("MemberMissing", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Method {0}.{1} is public. Use strong-typed Expect overload instead: + ///mock.Setup(x => x.{1}()); + ///. + /// + internal static string MethodIsPublic { + get { + return ResourceManager.GetString("MethodIsPublic", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to {0} invocation failed with mock behavior {1}. + ///{2}. + /// + internal static string MockExceptionMessage { + get { + return ResourceManager.GetString("MockExceptionMessage", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Expected only {0} calls to {1}.. + /// + internal static string MoreThanNCalls { + get { + return ResourceManager.GetString("MoreThanNCalls", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Expected only one call to {0}.. + /// + internal static string MoreThanOneCall { + get { + return ResourceManager.GetString("MoreThanOneCall", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to {0} + ///Expected invocation on the mock at least {2} times, but was {4} times: {1}. + /// + internal static string NoMatchingCallsAtLeast { + get { + return ResourceManager.GetString("NoMatchingCallsAtLeast", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to {0} + ///Expected invocation on the mock at least once, but was never performed: {1}. + /// + internal static string NoMatchingCallsAtLeastOnce { + get { + return ResourceManager.GetString("NoMatchingCallsAtLeastOnce", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to {0} + ///Expected invocation on the mock at most {3} times, but was {4} times: {1}. + /// + internal static string NoMatchingCallsAtMost { + get { + return ResourceManager.GetString("NoMatchingCallsAtMost", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to {0} + ///Expected invocation on the mock at most once, but was {4} times: {1}. + /// + internal static string NoMatchingCallsAtMostOnce { + get { + return ResourceManager.GetString("NoMatchingCallsAtMostOnce", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to {0} + ///Expected invocation on the mock between {2} and {3} times (Exclusive), but was {4} times: {1}. + /// + internal static string NoMatchingCallsBetweenExclusive { + get { + return ResourceManager.GetString("NoMatchingCallsBetweenExclusive", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to {0} + ///Expected invocation on the mock between {2} and {3} times (Inclusive), but was {4} times: {1}. + /// + internal static string NoMatchingCallsBetweenInclusive { + get { + return ResourceManager.GetString("NoMatchingCallsBetweenInclusive", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to {0} + ///Expected invocation on the mock exactly {2} times, but was {4} times: {1}. + /// + internal static string NoMatchingCallsExactly { + get { + return ResourceManager.GetString("NoMatchingCallsExactly", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to {0} + ///Expected invocation on the mock should never have been performed, but was {4} times: {1}. + /// + internal static string NoMatchingCallsNever { + get { + return ResourceManager.GetString("NoMatchingCallsNever", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to {0} + ///Expected invocation on the mock once, but was {4} times: {1}. + /// + internal static string NoMatchingCallsOnce { + get { + return ResourceManager.GetString("NoMatchingCallsOnce", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to All invocations on the mock must have a corresponding setup.. + /// + internal static string NoSetup { + get { + return ResourceManager.GetString("NoSetup", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Object instance was not created by Moq.. + /// + internal static string ObjectInstanceNotMock { + get { + return ResourceManager.GetString("ObjectInstanceNotMock", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Out expression must evaluate to a constant value.. + /// + internal static string OutExpressionMustBeConstantValue { + get { + return ResourceManager.GetString("OutExpressionMustBeConstantValue", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Property {0}.{1} does not have a getter.. + /// + internal static string PropertyGetNotFound { + get { + return ResourceManager.GetString("PropertyGetNotFound", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Property {0}.{1} does not exist.. + /// + internal static string PropertyMissing { + get { + return ResourceManager.GetString("PropertyMissing", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Property {0}.{1} is write-only.. + /// + internal static string PropertyNotReadable { + get { + return ResourceManager.GetString("PropertyNotReadable", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Property {0}.{1} is read-only.. + /// + internal static string PropertyNotWritable { + get { + return ResourceManager.GetString("PropertyNotWritable", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Property {0}.{1} does not have a setter.. + /// + internal static string PropertySetNotFound { + get { + return ResourceManager.GetString("PropertySetNotFound", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Cannot raise a mocked event unless it has been associated (attached) to a concrete event in a mocked object.. + /// + internal static string RaisedUnassociatedEvent { + get { + return ResourceManager.GetString("RaisedUnassociatedEvent", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Ref expression must evaluate to a constant value.. + /// + internal static string RefExpressionMustBeConstantValue { + get { + return ResourceManager.GetString("RefExpressionMustBeConstantValue", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Invocation needs to return a value and therefore must have a corresponding setup that provides it.. + /// + internal static string ReturnValueRequired { + get { + return ResourceManager.GetString("ReturnValueRequired", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to A lambda expression is expected as the argument to It.Is<T>.. + /// + internal static string SetupLambda { + get { + return ResourceManager.GetString("SetupLambda", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Invocation {0} should not have been made.. + /// + internal static string SetupNever { + get { + return ResourceManager.GetString("SetupNever", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Expression is not a method invocation: {0}. + /// + internal static string SetupNotMethod { + get { + return ResourceManager.GetString("SetupNotMethod", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Expression is not a property access: {0}. + /// + internal static string SetupNotProperty { + get { + return ResourceManager.GetString("SetupNotProperty", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Expression is not a property setter invocation.. + /// + internal static string SetupNotSetter { + get { + return ResourceManager.GetString("SetupNotSetter", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Expression references a method that does not belong to the mocked object: {0}. + /// + internal static string SetupOnNonMemberMethod { + get { + return ResourceManager.GetString("SetupOnNonMemberMethod", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Invalid setup on a non-virtual (overridable in VB) member: {0}. + /// + internal static string SetupOnNonOverridableMember { + get { + return ResourceManager.GetString("SetupOnNonOverridableMember", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Type {0} does not implement required interface {1}. + /// + internal static string TypeNotImplementInterface { + get { + return ResourceManager.GetString("TypeNotImplementInterface", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Type {0} does not from required type {1}. + /// + internal static string TypeNotInheritFromType { + get { + return ResourceManager.GetString("TypeNotInheritFromType", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to To specify a setup for public property {0}.{1}, use the typed overloads, such as: + ///mock.Setup(x => x.{1}).Returns(value); + ///mock.SetupGet(x => x.{1}).Returns(value); //equivalent to previous one + ///mock.SetupSet(x => x.{1}).Callback(callbackDelegate); + ///. + /// + internal static string UnexpectedPublicProperty { + get { + return ResourceManager.GetString("UnexpectedPublicProperty", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Unsupported expression: {0}. + /// + internal static string UnsupportedExpression { + get { + return ResourceManager.GetString("UnsupportedExpression", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Only property accesses are supported in intermediate invocations on a setup. Unsupported expression {0}.. + /// + internal static string UnsupportedIntermediateExpression { + get { + return ResourceManager.GetString("UnsupportedIntermediateExpression", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Expression contains intermediate property access {0}.{1} which is of type {2} and cannot be mocked. Unsupported expression {3}.. + /// + internal static string UnsupportedIntermediateType { + get { + return ResourceManager.GetString("UnsupportedIntermediateType", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Setter expression cannot use argument matchers that receive parameters.. + /// + internal static string UnsupportedMatcherParamsForSetter { + get { + return ResourceManager.GetString("UnsupportedMatcherParamsForSetter", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Member {0} is not supported for protected mocking.. + /// + internal static string UnsupportedMember { + get { + return ResourceManager.GetString("UnsupportedMember", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Setter expression can only use static custom matchers.. + /// + internal static string UnsupportedNonStaticMatcherForSetter { + get { + return ResourceManager.GetString("UnsupportedNonStaticMatcherForSetter", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to The following setups were not matched: + ///{0}. + /// + internal static string VerficationFailed { + get { + return ResourceManager.GetString("VerficationFailed", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Invalid verify on a non-virtual (overridable in VB) member: {0}. + /// + internal static string VerifyOnNonVirtualMember { + get { + return ResourceManager.GetString("VerifyOnNonVirtualMember", resourceCulture); + } + } + } } diff --git a/Source/Properties/Resources.resx b/Source/Properties/Resources.resx index 62e4dd9c3..f8fe50554 100644 --- a/Source/Properties/Resources.resx +++ b/Source/Properties/Resources.resx @@ -1,310 +1,310 @@  - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - text/microsoft-resx - - - 2.0 - - - System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 - - - System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 - - - Expression {0} involves a field access, which is not supported. Use properties instead. - - - Type to mock must be an interface or an abstract or non-sealed class. - - - {0} invocation failed with mock behavior {1}. + mimetype: application/x-microsoft.net.object.bytearray.base64 + value : The object must be serialized into a byte array + : using a System.ComponentModel.TypeConverter + : and then encoded with base64 encoding. + --> + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + text/microsoft-resx + + + 2.0 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + Expression {0} involves a field access, which is not supported. Use properties instead. + + + Type to mock must be an interface or an abstract or non-sealed class. + + + {0} invocation failed with mock behavior {1}. {2} - - - Property {0}.{1} is write-only. - - - Unsupported expression: {0} - - - All invocations on the mock must have a corresponding setup. - - - Invocation needs to return a value and therefore must have a corresponding setup that provides it. - - - The following setups were not matched: + + + Property {0}.{1} is write-only. + + + Unsupported expression: {0} + + + All invocations on the mock must have a corresponding setup. + + + Invocation needs to return a value and therefore must have a corresponding setup that provides it. + + + The following setups were not matched: {0} - - - Invalid setup on a non-virtual (overridable in VB) member: {0} - - - Constructor arguments cannot be passed for interface mocks. - - - Constructor arguments cannot be passed for delegate mocks. - - - A matching constructor for the given arguments was not found on the mocked type. - - - Expected only one call to {0}. - - - Object instance was not created by Moq. - - - Property {0}.{1} is read-only. - - - Expression is not a property access: {0} - - - A lambda expression is expected as the argument to It.Is<T>. - - - Method {0}.{1} is public. Use strong-typed Expect overload instead: + + + Invalid setup on a non-virtual (overridable in VB) member: {0} + + + Constructor arguments cannot be passed for interface mocks. + + + Constructor arguments cannot be passed for delegate mocks. + + + A matching constructor for the given arguments was not found on the mocked type. + + + Expected only one call to {0}. + + + Object instance was not created by Moq. + + + Property {0}.{1} is read-only. + + + Expression is not a property access: {0} + + + A lambda expression is expected as the argument to It.Is<T>. + + + Method {0}.{1} is public. Use strong-typed Expect overload instead: mock.Setup(x => x.{1}()); - - - Member {0}.{1} does not exist. - - - To specify a setup for public property {0}.{1}, use the typed overloads, such as: + + + Member {0}.{1} does not exist. + + + To specify a setup for public property {0}.{1}, use the typed overloads, such as: mock.Setup(x => x.{1}).Returns(value); mock.SetupGet(x => x.{1}).Returns(value); //equivalent to previous one mock.SetupSet(x => x.{1}).Callback(callbackDelegate); - - - Property {0}.{1} does not exist. - - - Can't set return value for void method {0}. - - - Member {0} is not supported for protected mocking. - - - Cannot raise a mocked event unless it has been associated (attached) to a concrete event in a mocked object. - - - Expression is not a method invocation: {0} - - - {0} + + + Property {0}.{1} does not exist. + + + Can't set return value for void method {0}. + + + Member {0} is not supported for protected mocking. + + + Cannot raise a mocked event unless it has been associated (attached) to a concrete event in a mocked object. + + + Expression is not a method invocation: {0} + + + {0} Expected invocation on the mock at least once, but was never performed: {1} - - - Mock type has already been initialized by accessing its Object property. Adding interfaces must be done before that. - - - Can only add interfaces to the mock. - - - Cannot retrieve a mock with the given object type {0} as it's not the main type of the mock or any of its additional interfaces. + + + Mock type has already been initialized by accessing its Object property. Adding interfaces must be done before that. + + + Can only add interfaces to the mock. + + + Cannot retrieve a mock with the given object type {0} as it's not the main type of the mock or any of its additional interfaces. Please cast the argument to one of the supported types: {1}. Remember that there's no generics covariance in the CLR, so your object must be one of these types in order for the call to succeed. - - - Invocation {0} should not have been made. - - - Only property accesses are supported in intermediate invocations on a setup. Unsupported expression {0}. - - - Expression contains intermediate property access {0}.{1} which is of type {2} and cannot be mocked. Unsupported expression {3}. - - - Expected only {0} calls to {1}. - - - Expression is not a property setter invocation. - - - Setter expression cannot use argument matchers that receive parameters. - - - Setter expression can only use static custom matchers. - - - Value cannot be an empty string. - - - Type {0} does not implement required interface {1} - - - Type {0} does not from required type {1} - - - {0} + + + Invocation {0} should not have been made. + + + Only property accesses are supported in intermediate invocations on a setup. Unsupported expression {0}. + + + Expression contains intermediate property access {0}.{1} which is of type {2} and cannot be mocked. Unsupported expression {3}. + + + Expected only {0} calls to {1}. + + + Expression is not a property setter invocation. + + + Setter expression cannot use argument matchers that receive parameters. + + + Setter expression can only use static custom matchers. + + + Value cannot be an empty string. + + + Type {0} does not implement required interface {1} + + + Type {0} does not from required type {1} + + + {0} Expected invocation on the mock at least {2} times, but was {4} times: {1} - - - {0} + + + {0} Expected invocation on the mock at most {3} times, but was {4} times: {1} - - - {0} + + + {0} Expected invocation on the mock at most once, but was {4} times: {1} - - - {0} + + + {0} Expected invocation on the mock between {2} and {3} times (Inclusive), but was {4} times: {1} - - - {0} + + + {0} Expected invocation on the mock exactly {2} times, but was {4} times: {1} - - - {0} + + + {0} Expected invocation on the mock should never have been performed, but was {4} times: {1} - - - {0} + + + {0} Expected invocation on the mock between {2} and {3} times (Exclusive), but was {4} times: {1} - - - {0} + + + {0} Expected invocation on the mock once, but was {4} times: {1} - - - Expression references a method that does not belong to the mocked object: {0} - - - Invalid verify on a non-virtual (overridable in VB) member: {0} - - - Out expression must evaluate to a constant value. - - - Ref expression must evaluate to a constant value. - - - LINQ method '{0}' not supported. - - - Could not locate event for attach or detach method {0}. - - - The equals ("==" or "=" in VB) and the conditional 'and' ("&&" or "AndAlso" in VB) operators are the only ones supported in the query specification expression. Unsupported expression: {0} - - - Expression contains a call to a method which is not virtual (overridable in VB) or abstract. Unsupported expression: {0} - - - Property {0}.{1} does not have a setter. - - - Property {0}.{1} does not have a getter. - + + + Expression references a method that does not belong to the mocked object: {0} + + + Invalid verify on a non-virtual (overridable in VB) member: {0} + + + Out expression must evaluate to a constant value. + + + Ref expression must evaluate to a constant value. + + + LINQ method '{0}' not supported. + + + Could not locate event for attach or detach method {0}. + + + The equals ("==" or "=" in VB) and the conditional 'and' ("&&" or "AndAlso" in VB) operators are the only ones supported in the query specification expression. Unsupported expression: {0} + + + Expression contains a call to a method which is not virtual (overridable in VB) or abstract. Unsupported expression: {0} + + + Property {0}.{1} does not have a setter. + + + Property {0}.{1} does not have a getter. + \ No newline at end of file diff --git a/Source/Protected/ProtectedExtension.cs b/Source/Protected/ProtectedExtension.cs index fcc16ebc0..0d6a7def8 100644 --- a/Source/Protected/ProtectedExtension.cs +++ b/Source/Protected/ProtectedExtension.cs @@ -62,4 +62,4 @@ public static IProtectedMock Protected(this Mock mock) return new ProtectedMock(mock); } } -} \ No newline at end of file +} diff --git a/Source/Protected/ProtectedMock.cs b/Source/Protected/ProtectedMock.cs index 00bf94006..af4fbfb73 100644 --- a/Source/Protected/ProtectedMock.cs +++ b/Source/Protected/ProtectedMock.cs @@ -389,4 +389,4 @@ private static IEnumerable ToExpressionArgs(MethodInfo method, objec } } } -} \ No newline at end of file +} diff --git a/Source/Proxy/CastleProxyFactory.cs b/Source/Proxy/CastleProxyFactory.cs index e48d29fc4..c824b4940 100644 --- a/Source/Proxy/CastleProxyFactory.cs +++ b/Source/Proxy/CastleProxyFactory.cs @@ -116,7 +116,7 @@ public Type GetDelegateProxyInterface(Type delegateType, out MethodInfo delegate lock (this) { if (!delegateInterfaceCache.TryGetValue(delegateType, out delegateInterfaceType)) - { + { var interfaceName = String.Format(CultureInfo.InvariantCulture, "DelegateInterface_{0}_{1}", delegateType.Name, delegateInterfaceSuffix++); @@ -141,8 +141,8 @@ public Type GetDelegateProxyInterface(Type delegateType, out MethodInfo delegate delegateInterfaceType = newTypeBuilder.CreateTypeInfo().AsType(); delegateInterfaceCache[delegateType] = delegateInterfaceType; - } - } + } + } delegateInterfaceMethod = delegateInterfaceType.GetMethod("Invoke"); return delegateInterfaceType; diff --git a/Source/Proxy/ICallContext.cs b/Source/Proxy/ICallContext.cs index 01440783f..883607931 100644 --- a/Source/Proxy/ICallContext.cs +++ b/Source/Proxy/ICallContext.cs @@ -55,4 +55,4 @@ internal interface ICallContext void SetArgumentValue(int index, object value); } -} \ No newline at end of file +} diff --git a/Source/Proxy/ICallInterceptor.cs b/Source/Proxy/ICallInterceptor.cs index d4cc0fa21..b1a559f89 100644 --- a/Source/Proxy/ICallInterceptor.cs +++ b/Source/Proxy/ICallInterceptor.cs @@ -44,4 +44,4 @@ internal interface ICallInterceptor { void Intercept(ICallContext context); } -} \ No newline at end of file +} diff --git a/Source/Proxy/IProxyFactory.cs b/Source/Proxy/IProxyFactory.cs index 9ea47b9cd..087f28eca 100644 --- a/Source/Proxy/IProxyFactory.cs +++ b/Source/Proxy/IProxyFactory.cs @@ -60,4 +60,4 @@ internal interface IProxyFactory /// The method on the autogenerated interface. Type GetDelegateProxyInterface(Type delegateType, out MethodInfo delegateInterfaceMethod); } -} \ No newline at end of file +} diff --git a/Source/Range.cs b/Source/Range.cs index 3574f42f6..101ccfd49 100644 --- a/Source/Range.cs +++ b/Source/Range.cs @@ -9,12 +9,12 @@ // * Redistributions of source code must retain the // above copyright notice, this list of conditions and // the following disclaimer. - + // * Redistributions in binary form must reproduce // the above copyright notice, this list of conditions // and the following disclaimer in the documentation // and/or other materials provided with the distribution. - + // * Neither the name of Clarius Consulting, Manas Technology Solutions or InSTEDD nor the // names of its contributors may be used to endorse // or promote products derived from this software @@ -51,10 +51,11 @@ public enum Range /// from values. /// Inclusive, + /// /// The range does not include the to and /// from values. /// Exclusive } -} \ No newline at end of file +} diff --git a/Source/ReturnsExtensions.Generated.cs b/Source/ReturnsExtensions.Generated.cs index 041a46494..fa72ed6ae 100644 --- a/Source/ReturnsExtensions.Generated.cs +++ b/Source/ReturnsExtensions.Generated.cs @@ -6,163 +6,163 @@ namespace Moq { - /// - /// Defines async extension methods on IReturns. - /// + /// + /// Defines async extension methods on IReturns. + /// public static class GeneratedReturnsExtensions { /// - /// Specifies a function that will calculate the value to return from the asynchronous method. - /// + /// Specifies a function that will calculate the value to return from the asynchronous method. + /// /// Type of the function parameter. - /// Mocked type. - /// Type of the return value. - /// Returns verb which represents the mocked type and the task of return type - /// The function that will calculate the return value. + /// Mocked type. + /// Type of the return value. + /// Returns verb which represents the mocked type and the task of return type + /// The function that will calculate the return value. public static IReturnsResult ReturnsAsync(this IReturns> mock, Func valueFunction) where TMock : class { return mock.Returns((T t) => Task.FromResult(valueFunction(t))); } /// - /// Specifies a function that will calculate the value to return from the asynchronous method. - /// - /// Returns verb which represents the mocked type and the task of return type - /// The function that will calculate the return value. + /// Specifies a function that will calculate the value to return from the asynchronous method. + /// + /// Returns verb which represents the mocked type and the task of return type + /// The function that will calculate the return value. public static IReturnsResult ReturnsAsync(this IReturns> mock, Func valueFunction) where TMock : class { return mock.Returns((T1 t1, T2 t2) => Task.FromResult(valueFunction(t1, t2))); } /// - /// Specifies a function that will calculate the value to return from the asynchronous method. - /// - /// Returns verb which represents the mocked type and the task of return type - /// The function that will calculate the return value. + /// Specifies a function that will calculate the value to return from the asynchronous method. + /// + /// Returns verb which represents the mocked type and the task of return type + /// The function that will calculate the return value. public static IReturnsResult ReturnsAsync(this IReturns> mock, Func valueFunction) where TMock : class { return mock.Returns((T1 t1, T2 t2, T3 t3) => Task.FromResult(valueFunction(t1, t2, t3))); } /// - /// Specifies a function that will calculate the value to return from the asynchronous method. - /// - /// Returns verb which represents the mocked type and the task of return type - /// The function that will calculate the return value. + /// Specifies a function that will calculate the value to return from the asynchronous method. + /// + /// Returns verb which represents the mocked type and the task of return type + /// The function that will calculate the return value. public static IReturnsResult ReturnsAsync(this IReturns> mock, Func valueFunction) where TMock : class { return mock.Returns((T1 t1, T2 t2, T3 t3, T4 t4) => Task.FromResult(valueFunction(t1, t2, t3, t4))); } /// - /// Specifies a function that will calculate the value to return from the asynchronous method. - /// - /// Returns verb which represents the mocked type and the task of return type - /// The function that will calculate the return value. + /// Specifies a function that will calculate the value to return from the asynchronous method. + /// + /// Returns verb which represents the mocked type and the task of return type + /// The function that will calculate the return value. public static IReturnsResult ReturnsAsync(this IReturns> mock, Func valueFunction) where TMock : class { return mock.Returns((T1 t1, T2 t2, T3 t3, T4 t4, T5 t5) => Task.FromResult(valueFunction(t1, t2, t3, t4, t5))); } /// - /// Specifies a function that will calculate the value to return from the asynchronous method. - /// - /// Returns verb which represents the mocked type and the task of return type - /// The function that will calculate the return value. + /// Specifies a function that will calculate the value to return from the asynchronous method. + /// + /// Returns verb which represents the mocked type and the task of return type + /// The function that will calculate the return value. public static IReturnsResult ReturnsAsync(this IReturns> mock, Func valueFunction) where TMock : class { return mock.Returns((T1 t1, T2 t2, T3 t3, T4 t4, T5 t5, T6 t6) => Task.FromResult(valueFunction(t1, t2, t3, t4, t5, t6))); } /// - /// Specifies a function that will calculate the value to return from the asynchronous method. - /// - /// Returns verb which represents the mocked type and the task of return type - /// The function that will calculate the return value. + /// Specifies a function that will calculate the value to return from the asynchronous method. + /// + /// Returns verb which represents the mocked type and the task of return type + /// The function that will calculate the return value. public static IReturnsResult ReturnsAsync(this IReturns> mock, Func valueFunction) where TMock : class { return mock.Returns((T1 t1, T2 t2, T3 t3, T4 t4, T5 t5, T6 t6, T7 t7) => Task.FromResult(valueFunction(t1, t2, t3, t4, t5, t6, t7))); } /// - /// Specifies a function that will calculate the value to return from the asynchronous method. - /// - /// Returns verb which represents the mocked type and the task of return type - /// The function that will calculate the return value. + /// Specifies a function that will calculate the value to return from the asynchronous method. + /// + /// Returns verb which represents the mocked type and the task of return type + /// The function that will calculate the return value. public static IReturnsResult ReturnsAsync(this IReturns> mock, Func valueFunction) where TMock : class { return mock.Returns((T1 t1, T2 t2, T3 t3, T4 t4, T5 t5, T6 t6, T7 t7, T8 t8) => Task.FromResult(valueFunction(t1, t2, t3, t4, t5, t6, t7, t8))); } /// - /// Specifies a function that will calculate the value to return from the asynchronous method. - /// - /// Returns verb which represents the mocked type and the task of return type - /// The function that will calculate the return value. + /// Specifies a function that will calculate the value to return from the asynchronous method. + /// + /// Returns verb which represents the mocked type and the task of return type + /// The function that will calculate the return value. public static IReturnsResult ReturnsAsync(this IReturns> mock, Func valueFunction) where TMock : class { return mock.Returns((T1 t1, T2 t2, T3 t3, T4 t4, T5 t5, T6 t6, T7 t7, T8 t8, T9 t9) => Task.FromResult(valueFunction(t1, t2, t3, t4, t5, t6, t7, t8, t9))); } /// - /// Specifies a function that will calculate the value to return from the asynchronous method. - /// - /// Returns verb which represents the mocked type and the task of return type - /// The function that will calculate the return value. + /// Specifies a function that will calculate the value to return from the asynchronous method. + /// + /// Returns verb which represents the mocked type and the task of return type + /// The function that will calculate the return value. public static IReturnsResult ReturnsAsync(this IReturns> mock, Func valueFunction) where TMock : class { return mock.Returns((T1 t1, T2 t2, T3 t3, T4 t4, T5 t5, T6 t6, T7 t7, T8 t8, T9 t9, T10 t10) => Task.FromResult(valueFunction(t1, t2, t3, t4, t5, t6, t7, t8, t9, t10))); } /// - /// Specifies a function that will calculate the value to return from the asynchronous method. - /// - /// Returns verb which represents the mocked type and the task of return type - /// The function that will calculate the return value. + /// Specifies a function that will calculate the value to return from the asynchronous method. + /// + /// Returns verb which represents the mocked type and the task of return type + /// The function that will calculate the return value. public static IReturnsResult ReturnsAsync(this IReturns> mock, Func valueFunction) where TMock : class { return mock.Returns((T1 t1, T2 t2, T3 t3, T4 t4, T5 t5, T6 t6, T7 t7, T8 t8, T9 t9, T10 t10, T11 t11) => Task.FromResult(valueFunction(t1, t2, t3, t4, t5, t6, t7, t8, t9, t10, t11))); } /// - /// Specifies a function that will calculate the value to return from the asynchronous method. - /// - /// Returns verb which represents the mocked type and the task of return type - /// The function that will calculate the return value. + /// Specifies a function that will calculate the value to return from the asynchronous method. + /// + /// Returns verb which represents the mocked type and the task of return type + /// The function that will calculate the return value. public static IReturnsResult ReturnsAsync(this IReturns> mock, Func valueFunction) where TMock : class { return mock.Returns((T1 t1, T2 t2, T3 t3, T4 t4, T5 t5, T6 t6, T7 t7, T8 t8, T9 t9, T10 t10, T11 t11, T12 t12) => Task.FromResult(valueFunction(t1, t2, t3, t4, t5, t6, t7, t8, t9, t10, t11, t12))); } /// - /// Specifies a function that will calculate the value to return from the asynchronous method. - /// - /// Returns verb which represents the mocked type and the task of return type - /// The function that will calculate the return value. + /// Specifies a function that will calculate the value to return from the asynchronous method. + /// + /// Returns verb which represents the mocked type and the task of return type + /// The function that will calculate the return value. public static IReturnsResult ReturnsAsync(this IReturns> mock, Func valueFunction) where TMock : class { return mock.Returns((T1 t1, T2 t2, T3 t3, T4 t4, T5 t5, T6 t6, T7 t7, T8 t8, T9 t9, T10 t10, T11 t11, T12 t12, T13 t13) => Task.FromResult(valueFunction(t1, t2, t3, t4, t5, t6, t7, t8, t9, t10, t11, t12, t13))); } /// - /// Specifies a function that will calculate the value to return from the asynchronous method. - /// - /// Returns verb which represents the mocked type and the task of return type - /// The function that will calculate the return value. + /// Specifies a function that will calculate the value to return from the asynchronous method. + /// + /// Returns verb which represents the mocked type and the task of return type + /// The function that will calculate the return value. public static IReturnsResult ReturnsAsync(this IReturns> mock, Func valueFunction) where TMock : class { return mock.Returns((T1 t1, T2 t2, T3 t3, T4 t4, T5 t5, T6 t6, T7 t7, T8 t8, T9 t9, T10 t10, T11 t11, T12 t12, T13 t13, T14 t14) => Task.FromResult(valueFunction(t1, t2, t3, t4, t5, t6, t7, t8, t9, t10, t11, t12, t13, t14))); } /// - /// Specifies a function that will calculate the value to return from the asynchronous method. - /// - /// Returns verb which represents the mocked type and the task of return type - /// The function that will calculate the return value. + /// Specifies a function that will calculate the value to return from the asynchronous method. + /// + /// Returns verb which represents the mocked type and the task of return type + /// The function that will calculate the return value. public static IReturnsResult ReturnsAsync(this IReturns> mock, Func valueFunction) where TMock : class { return mock.Returns((T1 t1, T2 t2, T3 t3, T4 t4, T5 t5, T6 t6, T7 t7, T8 t8, T9 t9, T10 t10, T11 t11, T12 t12, T13 t13, T14 t14, T15 t15) => Task.FromResult(valueFunction(t1, t2, t3, t4, t5, t6, t7, t8, t9, t10, t11, t12, t13, t14, t15))); } } } -#endif \ No newline at end of file +#endif diff --git a/Source/ReturnsExtensions.cs b/Source/ReturnsExtensions.cs index 3ba16ccc6..e71154d18 100644 --- a/Source/ReturnsExtensions.cs +++ b/Source/ReturnsExtensions.cs @@ -6,176 +6,176 @@ namespace Moq { - /// - /// Defines async extension methods on IReturns. - /// - public static class ReturnsExtensions - { - /// - /// Specifies the value to return from an asynchronous method. - /// - /// Mocked type. - /// Type of the return value. - /// Returns verb which represents the mocked type and the task of return type - /// The value to return, or . - public static IReturnsResult ReturnsAsync(this IReturns> mock, TResult value) where TMock : class - { - return mock.ReturnsAsync(() => value); - } - - /// - /// Specifies a function that will calculate the value to return from the asynchronous method. - /// - /// Mocked type. - /// Type of the return value. - /// Returns verb which represents the mocked type and the task of return type - /// The function that will calculate the return value. - public static IReturnsResult ReturnsAsync(this IReturns> mock, Func valueFunction) where TMock : class + /// + /// Defines async extension methods on IReturns. + /// + public static class ReturnsExtensions + { + /// + /// Specifies the value to return from an asynchronous method. + /// + /// Mocked type. + /// Type of the return value. + /// Returns verb which represents the mocked type and the task of return type + /// The value to return, or . + public static IReturnsResult ReturnsAsync(this IReturns> mock, TResult value) where TMock : class { - return mock.Returns(() => Task.FromResult(valueFunction())); + return mock.ReturnsAsync(() => value); } - /// - /// Specifies the exception to throw when the asynchronous method is invoked. - /// - /// Mocked type. - /// Returns verb which represents the mocked type and the task return type - /// Exception instance to throw. - public static IReturnsResult ThrowsAsync(this IReturns mock, Exception exception) where TMock : class - { - var tcs = new TaskCompletionSource(); - tcs.SetException(exception); - - return mock.Returns(tcs.Task); - } - - /// - /// Specifies the exception to throw when the asynchronous method is invoked. - /// - /// Mocked type. - /// Type of the return value. - /// Returns verb which represents the mocked type and the task of return type - /// Exception instance to throw. - public static IReturnsResult ThrowsAsync(this IReturns> mock, Exception exception) where TMock : class - { - var tcs = new TaskCompletionSource(); - tcs.SetException(exception); - - return mock.Returns(tcs.Task); - } - - private static readonly Random Random = new Random(); - - /// - /// Allows to specify the delayed return value of an asynchronous method. - /// - public static IReturnsResult ReturnsAsync(this IReturns> mock, - TResult value, TimeSpan delay) where TMock : class - { - return DelayedResult(mock, value, delay); - } - - /// - /// Allows to specify the delayed return value of an asynchronous method. - /// - public static IReturnsResult ReturnsAsync(this IReturns> mock, - TResult value, TimeSpan minDelay, TimeSpan maxDelay) where TMock : class - { - var delay = GetDelay(minDelay, maxDelay, Random); - - return DelayedResult(mock, value, delay); - } - - /// - /// Allows to specify the delayed return value of an asynchronous method. - /// Use the argument to pass in (seeded) random generators used across your unit test. - /// - public static IReturnsResult ReturnsAsync(this IReturns> mock, - TResult value, TimeSpan minDelay, TimeSpan maxDelay, Random random) where TMock : class - { - if(random == null) - throw new ArgumentNullException(nameof(random)); - - var delay = GetDelay(minDelay, maxDelay, random); - - return DelayedResult(mock, value, delay); - } - - /// - /// Allows to specify the exception thrown by an asynchronous method. - /// - public static IReturnsResult ThrowsAsync(this IReturns> mock, - Exception exception, TimeSpan delay) where TMock : class - { - return DelayedException(mock, exception, delay); - } - - /// - /// Allows to specify the exception thrown by an asynchronous method. - /// - public static IReturnsResult ThrowsAsync(this IReturns> mock, - Exception exception, TimeSpan minDelay, TimeSpan maxDelay) where TMock : class - { - var delay = GetDelay(minDelay, maxDelay, Random); - - return DelayedException(mock, exception, delay); - } - - /// - /// Allows to specify the exception thrown by an asynchronous method. - /// Use the argument to pass in (seeded) random generators used across your unit test. - /// - public static IReturnsResult ThrowsAsync(this IReturns> mock, - Exception exception, TimeSpan minDelay, TimeSpan maxDelay, Random random) where TMock : class - { - if (random == null) - throw new ArgumentNullException(nameof(random)); - - var delay = GetDelay(minDelay, maxDelay, random); - - return DelayedException(mock, exception, delay); - } - - private static TimeSpan GetDelay(TimeSpan minDelay, TimeSpan maxDelay, Random random) - { - if (!(minDelay < maxDelay)) - throw new ArgumentException("Mininum delay has to be lower than maximum delay."); - - var min = (int)minDelay.Ticks; - var max = (int)maxDelay.Ticks; - - return new TimeSpan(random.Next(min, max)); - } - - private static void GuardPositiveDelay(TimeSpan delay) - { - if (!(delay > TimeSpan.Zero)) - throw new ArgumentException("Delays have to be greater than zero to ensure an async callback is used."); - } - - private static IReturnsResult DelayedResult(IReturns> mock, - TResult value, TimeSpan delay) - where TMock : class - { - GuardPositiveDelay(delay); - - var tcs = new TaskCompletionSource(); - Task.Delay(delay).ContinueWith(t => tcs.SetResult(value)); - - return mock.Returns(tcs.Task); - } - - private static IReturnsResult DelayedException(IReturns> mock, - Exception exception, TimeSpan delay) - where TMock : class - { - GuardPositiveDelay(delay); - - var tcs = new TaskCompletionSource(); - Task.Delay(delay).ContinueWith(t => tcs.SetException(exception)); - - return mock.Returns(tcs.Task); - } - } + /// + /// Specifies a function that will calculate the value to return from the asynchronous method. + /// + /// Mocked type. + /// Type of the return value. + /// Returns verb which represents the mocked type and the task of return type + /// The function that will calculate the return value. + public static IReturnsResult ReturnsAsync(this IReturns> mock, Func valueFunction) where TMock : class + { + return mock.Returns(() => Task.FromResult(valueFunction())); + } + + /// + /// Specifies the exception to throw when the asynchronous method is invoked. + /// + /// Mocked type. + /// Returns verb which represents the mocked type and the task return type + /// Exception instance to throw. + public static IReturnsResult ThrowsAsync(this IReturns mock, Exception exception) where TMock : class + { + var tcs = new TaskCompletionSource(); + tcs.SetException(exception); + + return mock.Returns(tcs.Task); + } + + /// + /// Specifies the exception to throw when the asynchronous method is invoked. + /// + /// Mocked type. + /// Type of the return value. + /// Returns verb which represents the mocked type and the task of return type + /// Exception instance to throw. + public static IReturnsResult ThrowsAsync(this IReturns> mock, Exception exception) where TMock : class + { + var tcs = new TaskCompletionSource(); + tcs.SetException(exception); + + return mock.Returns(tcs.Task); + } + + private static readonly Random Random = new Random(); + + /// + /// Allows to specify the delayed return value of an asynchronous method. + /// + public static IReturnsResult ReturnsAsync(this IReturns> mock, + TResult value, TimeSpan delay) where TMock : class + { + return DelayedResult(mock, value, delay); + } + + /// + /// Allows to specify the delayed return value of an asynchronous method. + /// + public static IReturnsResult ReturnsAsync(this IReturns> mock, + TResult value, TimeSpan minDelay, TimeSpan maxDelay) where TMock : class + { + var delay = GetDelay(minDelay, maxDelay, Random); + + return DelayedResult(mock, value, delay); + } + + /// + /// Allows to specify the delayed return value of an asynchronous method. + /// Use the argument to pass in (seeded) random generators used across your unit test. + /// + public static IReturnsResult ReturnsAsync(this IReturns> mock, + TResult value, TimeSpan minDelay, TimeSpan maxDelay, Random random) where TMock : class + { + if(random == null) + throw new ArgumentNullException(nameof(random)); + + var delay = GetDelay(minDelay, maxDelay, random); + + return DelayedResult(mock, value, delay); + } + + /// + /// Allows to specify the exception thrown by an asynchronous method. + /// + public static IReturnsResult ThrowsAsync(this IReturns> mock, + Exception exception, TimeSpan delay) where TMock : class + { + return DelayedException(mock, exception, delay); + } + + /// + /// Allows to specify the exception thrown by an asynchronous method. + /// + public static IReturnsResult ThrowsAsync(this IReturns> mock, + Exception exception, TimeSpan minDelay, TimeSpan maxDelay) where TMock : class + { + var delay = GetDelay(minDelay, maxDelay, Random); + + return DelayedException(mock, exception, delay); + } + + /// + /// Allows to specify the exception thrown by an asynchronous method. + /// Use the argument to pass in (seeded) random generators used across your unit test. + /// + public static IReturnsResult ThrowsAsync(this IReturns> mock, + Exception exception, TimeSpan minDelay, TimeSpan maxDelay, Random random) where TMock : class + { + if (random == null) + throw new ArgumentNullException(nameof(random)); + + var delay = GetDelay(minDelay, maxDelay, random); + + return DelayedException(mock, exception, delay); + } + + private static TimeSpan GetDelay(TimeSpan minDelay, TimeSpan maxDelay, Random random) + { + if (!(minDelay < maxDelay)) + throw new ArgumentException("Mininum delay has to be lower than maximum delay."); + + var min = (int)minDelay.Ticks; + var max = (int)maxDelay.Ticks; + + return new TimeSpan(random.Next(min, max)); + } + + private static void GuardPositiveDelay(TimeSpan delay) + { + if (!(delay > TimeSpan.Zero)) + throw new ArgumentException("Delays have to be greater than zero to ensure an async callback is used."); + } + + private static IReturnsResult DelayedResult(IReturns> mock, + TResult value, TimeSpan delay) + where TMock : class + { + GuardPositiveDelay(delay); + + var tcs = new TaskCompletionSource(); + Task.Delay(delay).ContinueWith(t => tcs.SetResult(value)); + + return mock.Returns(tcs.Task); + } + + private static IReturnsResult DelayedException(IReturns> mock, + Exception exception, TimeSpan delay) + where TMock : class + { + GuardPositiveDelay(delay); + + var tcs = new TaskCompletionSource(); + Task.Delay(delay).ContinueWith(t => tcs.SetException(exception)); + + return mock.Returns(tcs.Task); + } + } } #endif diff --git a/Source/ReturnsExtensions.tt b/Source/ReturnsExtensions.tt index a3d7b914f..009c712b3 100644 --- a/Source/ReturnsExtensions.tt +++ b/Source/ReturnsExtensions.tt @@ -10,19 +10,19 @@ using Moq.Language.Flow; namespace Moq { - /// - /// Defines async extension methods on IReturns. - /// + /// + /// Defines async extension methods on IReturns. + /// public static class GeneratedReturnsExtensions { /// - /// Specifies a function that will calculate the value to return from the asynchronous method. - /// + /// Specifies a function that will calculate the value to return from the asynchronous method. + /// /// Type of the function parameter. - /// Mocked type. - /// Type of the return value. - /// Returns verb which represents the mocked type and the task of return type - /// The function that will calculate the return value. + /// Mocked type. + /// Type of the return value. + /// Returns verb which represents the mocked type and the task of return type + /// The function that will calculate the return value. public static IReturnsResult ReturnsAsync(this IReturns> mock, Func valueFunction) where TMock : class { return mock.Returns((T t) => Task.FromResult(valueFunction(t))); @@ -31,10 +31,10 @@ namespace Moq for (var argumentCount = 2; argumentCount <= 15; ++argumentCount) { #> /// - /// Specifies a function that will calculate the value to return from the asynchronous method. - /// - /// Returns verb which represents the mocked type and the task of return type - /// The function that will calculate the return value. + /// Specifies a function that will calculate the value to return from the asynchronous method. + /// + /// Returns verb which represents the mocked type and the task of return type + /// The function that will calculate the return value. public static IReturnsResult ReturnsAsync<<# for (var i = 1; i <= argumentCount; ++i) { @@ -61,4 +61,4 @@ namespace Moq #> } } -#endif \ No newline at end of file +#endif diff --git a/Source/SerializableTypesValueProvider.cs b/Source/SerializableTypesValueProvider.cs index c7d4636ba..b23494669 100644 --- a/Source/SerializableTypesValueProvider.cs +++ b/Source/SerializableTypesValueProvider.cs @@ -36,8 +36,8 @@ public void DefineDefault(T value) public object ProvideDefault(MethodInfo member) { return !member.ReturnType.GetTypeInfo().IsSerializable || member.ReturnType.IsSerializableMockable() - ? decorated.ProvideDefault(member) - : emptyDefaultValueProvider.ProvideDefault(member); + ? decorated.ProvideDefault(member) + : emptyDefaultValueProvider.ProvideDefault(member); } } -} \ No newline at end of file +} diff --git a/Source/SetterMethodCall.cs b/Source/SetterMethodCall.cs index 8e9b808d9..8f493ba14 100644 --- a/Source/SetterMethodCall.cs +++ b/Source/SetterMethodCall.cs @@ -70,4 +70,4 @@ public ICallbackResult Callback(Action callback) return this; } } -} \ No newline at end of file +} diff --git a/Source/SetupSequentialContext.cs b/Source/SetupSequentialContext.cs index af40a1a55..5e7974eab 100644 --- a/Source/SetupSequentialContext.cs +++ b/Source/SetupSequentialContext.cs @@ -57,8 +57,8 @@ public ISetupSequentialResult Returns(TResult value) public ISetupSequentialResult Throws(Exception exception) { - var setup = this.GetSetup(); - setup.Throws(exception); + var setup = this.GetSetup(); + setup.Throws(exception); this.EndSetup(setup); return this; } @@ -71,4 +71,4 @@ public ISetupSequentialResult Throws() where TException : E return this; } } -} \ No newline at end of file +} diff --git a/Source/Times.cs b/Source/Times.cs index 8f07c8ed5..ecb8668e8 100644 --- a/Source/Times.cs +++ b/Source/Times.cs @@ -181,4 +181,4 @@ internal bool Verify(int callCount) return this.evaluator(callCount); } } -} \ No newline at end of file +} diff --git a/Source/Times.xdoc b/Source/Times.xdoc index b85a1e582..544d51dcb 100644 --- a/Source/Times.xdoc +++ b/Source/Times.xdoc @@ -109,4 +109,4 @@ true if the value of left is different from the value of right; otherwise, false. - \ No newline at end of file + diff --git a/Source/project.json b/Source/project.json index 168c9b3e6..f418b3682 100644 --- a/Source/project.json +++ b/Source/project.json @@ -1,13 +1,13 @@ { - "dependencies": { - "Castle.Core": "4.0.0", - "IFluentInterface": "2.0.0", - "GitInfo": "1.1.15" - }, - "frameworks": { - "net45": { } - }, - "runtimes": { - "win": {} - } -} \ No newline at end of file + "dependencies": { + "Castle.Core": "4.0.0", + "IFluentInterface": "2.0.0", + "GitInfo": "1.1.15" + }, + "frameworks": { + "net45": { } + }, + "runtimes": { + "win": {} + } +} diff --git a/UnitTests.Visualizer/MockContextViewModelFixture.cs b/UnitTests.Visualizer/MockContextViewModelFixture.cs index 2ab79d2e6..2b980d3f0 100644 --- a/UnitTests.Visualizer/MockContextViewModelFixture.cs +++ b/UnitTests.Visualizer/MockContextViewModelFixture.cs @@ -92,4 +92,4 @@ public void AddExpandedMockViewModelToInnerMockContainers() Assert.True(call.IsExpanded); } } -} \ No newline at end of file +} diff --git a/UnitTests.Visualizer/Moq.Visualizer.Tests.csproj b/UnitTests.Visualizer/Moq.Visualizer.Tests.csproj index 89bff8667..cd97dcfb0 100644 --- a/UnitTests.Visualizer/Moq.Visualizer.Tests.csproj +++ b/UnitTests.Visualizer/Moq.Visualizer.Tests.csproj @@ -1,115 +1,115 @@  - - Debug - AnyCPU - 9.0.30729 - 2.0 - {A84563A0-8A70-43D9-A1C0-530955413318} - Library - Properties - Moq.Visualizer.Tests - Moq.Visualizer.Tests - v4.0 - 512 - true - ..\Moq.snk - - - 3.5 - - publish\ - true - Disk - false - Foreground - 7 - Days - false - false - true - 0 - 1.0.0.%2a - false - false - true - - - - true - full - false - bin\Debug\ - DEBUG;TRACE - prompt - 4 - AllRules.ruleset - - - pdbonly - true - bin\Release\ - TRACE - prompt - 4 - AllRules.ruleset - - - - - 3.5 - - - - - False - ..\Lib\xUnit\xunit.dll - - - - - - - - - - {1C91AC30-5977-4BE5-BA67-8EB186C03514} - Moq - - - - - Moq.snk - - - - - False - .NET Framework 3.5 SP1 Client Profile - false - - - False - .NET Framework 3.5 SP1 - true - - - False - Microsoft Visual Basic PowerPacks 10.0 - true - - - False - Windows Installer 3.1 - true - - - - - \ No newline at end of file + + Debug + AnyCPU + 9.0.30729 + 2.0 + {A84563A0-8A70-43D9-A1C0-530955413318} + Library + Properties + Moq.Visualizer.Tests + Moq.Visualizer.Tests + v4.0 + 512 + true + ..\Moq.snk + + + 3.5 + + publish\ + true + Disk + false + Foreground + 7 + Days + false + false + true + 0 + 1.0.0.%2a + false + false + true + + + + true + full + false + bin\Debug\ + DEBUG;TRACE + prompt + 4 + AllRules.ruleset + + + pdbonly + true + bin\Release\ + TRACE + prompt + 4 + AllRules.ruleset + + + + + 3.5 + + + + + False + ..\Lib\xUnit\xunit.dll + + + + + + + + + + {1C91AC30-5977-4BE5-BA67-8EB186C03514} + Moq + + + + + Moq.snk + + + + + False + .NET Framework 3.5 SP1 Client Profile + false + + + False + .NET Framework 3.5 SP1 + true + + + False + Microsoft Visual Basic PowerPacks 10.0 + true + + + False + Windows Installer 3.1 + true + + + + + diff --git a/UnitTests.Visualizer/SetupViewModelFixture.cs b/UnitTests.Visualizer/SetupViewModelFixture.cs index a74b20da1..5d1f958e5 100644 --- a/UnitTests.Visualizer/SetupViewModelFixture.cs +++ b/UnitTests.Visualizer/SetupViewModelFixture.cs @@ -53,4 +53,4 @@ public void CtorSetsIsExpandedAsFalse() Assert.False(target.IsExpanded); } } -} \ No newline at end of file +} diff --git a/UnitTests/AdvancedMatcherAttributeFixture.cs b/UnitTests/AdvancedMatcherAttributeFixture.cs index 3a39449d5..be10dbb0c 100644 --- a/UnitTests/AdvancedMatcherAttributeFixture.cs +++ b/UnitTests/AdvancedMatcherAttributeFixture.cs @@ -75,4 +75,4 @@ public bool Matches(object value) } } } -} \ No newline at end of file +} diff --git a/UnitTests/CaptureFixture.cs b/UnitTests/CaptureFixture.cs index 942aa1515..7a42a260c 100644 --- a/UnitTests/CaptureFixture.cs +++ b/UnitTests/CaptureFixture.cs @@ -3,38 +3,38 @@ namespace Moq.Tests { - public class CaptureFixture - { - [Fact] - public void CanCaptureAnyParameterInCollection() - { - var items = new List(); - var mock = new Mock(); - mock.Setup(x => x.DoSomething(Capture.In(items))); + public class CaptureFixture + { + [Fact] + public void CanCaptureAnyParameterInCollection() + { + var items = new List(); + var mock = new Mock(); + mock.Setup(x => x.DoSomething(Capture.In(items))); - mock.Object.DoSomething("Hello!"); + mock.Object.DoSomething("Hello!"); - var expectedValues = new List { "Hello!" }; - Assert.Equal(expectedValues, items); - } + var expectedValues = new List { "Hello!" }; + Assert.Equal(expectedValues, items); + } - [Fact] - public void CanCaptureSpecificParameterInCollection() - { - var items = new List(); - var mock = new Mock(); - mock.Setup(x => x.DoSomething(Capture.In(items, p => p.StartsWith("W")))); + [Fact] + public void CanCaptureSpecificParameterInCollection() + { + var items = new List(); + var mock = new Mock(); + mock.Setup(x => x.DoSomething(Capture.In(items, p => p.StartsWith("W")))); - mock.Object.DoSomething("Hello!"); - mock.Object.DoSomething("World!"); + mock.Object.DoSomething("Hello!"); + mock.Object.DoSomething("World!"); - var expectedValues = new List { "World!" }; - Assert.Equal(expectedValues, items); - } + var expectedValues = new List { "World!" }; + Assert.Equal(expectedValues, items); + } - public interface IFoo - { - void DoSomething(string s); - } - } -} \ No newline at end of file + public interface IFoo + { + void DoSomething(string s); + } + } +} diff --git a/UnitTests/CaptureMatchFixture.cs b/UnitTests/CaptureMatchFixture.cs index eeeba0390..a937110d4 100644 --- a/UnitTests/CaptureMatchFixture.cs +++ b/UnitTests/CaptureMatchFixture.cs @@ -2,40 +2,40 @@ namespace Moq.Tests { - public class CaptureMatchFixture - { - [Fact] - public void CanRunCaptureCallback() - { - var capturedValue = string.Empty; - var captureMatch = new CaptureMatch(s => capturedValue = s); - - var mock = new Mock(); - mock.Setup(x => x.DoSomething(Capture.With(captureMatch))); - - mock.Object.DoSomething("Hello!"); - - Assert.Equal("Hello!", capturedValue); - } - - [Fact] - public void CanRunCaptureCallbackWithPredicate() - { - var capturedValue = string.Empty; - var captureMatch = new CaptureMatch(s => capturedValue += s, s => s.StartsWith("W")); - - var mock = new Mock(); - mock.Setup(x => x.DoSomething(Capture.With(captureMatch))); - - mock.Object.DoSomething("Hello!"); - mock.Object.DoSomething("World!"); - - Assert.Equal("World!", capturedValue); - } - - public interface IFoo - { - void DoSomething(string item); - } - } -} \ No newline at end of file + public class CaptureMatchFixture + { + [Fact] + public void CanRunCaptureCallback() + { + var capturedValue = string.Empty; + var captureMatch = new CaptureMatch(s => capturedValue = s); + + var mock = new Mock(); + mock.Setup(x => x.DoSomething(Capture.With(captureMatch))); + + mock.Object.DoSomething("Hello!"); + + Assert.Equal("Hello!", capturedValue); + } + + [Fact] + public void CanRunCaptureCallbackWithPredicate() + { + var capturedValue = string.Empty; + var captureMatch = new CaptureMatch(s => capturedValue += s, s => s.StartsWith("W")); + + var mock = new Mock(); + mock.Setup(x => x.DoSomething(Capture.With(captureMatch))); + + mock.Object.DoSomething("Hello!"); + mock.Object.DoSomething("World!"); + + Assert.Equal("World!", capturedValue); + } + + public interface IFoo + { + void DoSomething(string item); + } + } +} diff --git a/UnitTests/ConditionalSetupFixture.cs b/UnitTests/ConditionalSetupFixture.cs index 44e0c0e62..68d4dd6d9 100644 --- a/UnitTests/ConditionalSetupFixture.cs +++ b/UnitTests/ConditionalSetupFixture.cs @@ -162,4 +162,4 @@ public interface IFoo string Foo(); } } -} \ No newline at end of file +} diff --git a/UnitTests/ExtensibilityFixture.cs b/UnitTests/ExtensibilityFixture.cs index 76f0d17ac..fdd75a14f 100644 --- a/UnitTests/ExtensibilityFixture.cs +++ b/UnitTests/ExtensibilityFixture.cs @@ -60,20 +60,20 @@ public void ShouldExtendWithPropertyMatchers() //[Fact] //public void SetterMatcherRendersNicely() //{ - // var mock = new Mock(); + // var mock = new Mock(); - // try - // { - // mock.VerifySet(repo => repo.Value = It.IsAny()); - // } - // catch (MockException me) - // { - // Console.WriteLine(me.Message); - // } + // try + // { + // mock.VerifySet(repo => repo.Value = It.IsAny()); + // } + // catch (MockException me) + // { + // Console.WriteLine(me.Message); + // } - // mock.Object.Value = 25; + // mock.Object.Value = 25; - // mock.VerifySet(repo => repo.Value = It.IsInRange(10, 25, Range.Inclusive)); + // mock.VerifySet(repo => repo.Value = It.IsInRange(10, 25, Range.Inclusive)); //} } diff --git a/UnitTests/ExtensionsFixture.cs b/UnitTests/ExtensionsFixture.cs index 7219fcdce..44679a837 100644 --- a/UnitTests/ExtensionsFixture.cs +++ b/UnitTests/ExtensionsFixture.cs @@ -6,97 +6,93 @@ namespace Moq.Tests { - public class ExtensionsFixture - { - #region Public Methods + public class ExtensionsFixture + { + #region Public Methods - [Fact] - public void IsMockeableReturnsFalseForValueType() - { - Assert.False(typeof(int).IsMockeable()); - } + [Fact] + public void IsMockeableReturnsFalseForValueType() + { + Assert.False(typeof(int).IsMockeable()); + } - [Fact] - public void OnceDoesNotThrowOnSecondCallIfCountWasResetBefore() - { - var mock = new Mock(); - mock.Setup(foo => foo.Execute("ping")).Returns("ack"); + [Fact] + public void OnceDoesNotThrowOnSecondCallIfCountWasResetBefore() + { + var mock = new Mock(); + mock.Setup(foo => foo.Execute("ping")).Returns("ack"); - mock.Object.Execute("ping"); - mock.ResetCalls(); - mock.Object.Execute("ping"); - mock.Verify(o => o.Execute("ping"), Times.Once()); - } + mock.Object.Execute("ping"); + mock.ResetCalls(); + mock.Object.Execute("ping"); + mock.Verify(o => o.Execute("ping"), Times.Once()); + } - [Fact] - public void SetupDoesNotApplyAfterMockWasReset() - { - var mock = new Mock(); - mock.Setup(foo => foo.Execute("ping")).Returns("ack"); - mock.Reset(); + [Fact] + public void SetupDoesNotApplyAfterMockWasReset() + { + var mock = new Mock(); + mock.Setup(foo => foo.Execute("ping")).Returns("ack"); + mock.Reset(); - var result = mock.Object.Execute("ping"); - Assert.Null(result); - } + var result = mock.Object.Execute("ping"); + Assert.Null(result); + } - [Fact] - - public void Loose() - { - var myMock = new Mock>(MockBehavior.Loose); - myMock - .Setup(a => a.ToString()) - .Returns("Hello"); - myMock.Reset(); - Assert.NotEqual("Hello", myMock.Object.ToString()); - myMock.VerifyAll(); - } + [Fact] + public void Loose() + { + var myMock = new Mock>(MockBehavior.Loose); + myMock + .Setup(a => a.ToString()) + .Returns("Hello"); + myMock.Reset(); + Assert.NotEqual("Hello", myMock.Object.ToString()); + myMock.VerifyAll(); + } - [Fact] - - public void Strict() - { - var myMock = new Mock>(MockBehavior.Strict); - myMock - .Setup(a => a.ToString()) - .Returns("Hello"); - myMock.Reset(); - Assert.NotEqual("Hello", myMock.Object.ToString()); - myMock.VerifyAll(); - } + [Fact] + public void Strict() + { + var myMock = new Mock>(MockBehavior.Strict); + myMock + .Setup(a => a.ToString()) + .Returns("Hello"); + myMock.Reset(); + Assert.NotEqual("Hello", myMock.Object.ToString()); + myMock.VerifyAll(); + } - [Fact] - - public void LooseNoCall() - { - var myMock = new Mock>(MockBehavior.Loose); - myMock - .Setup(a => a.ToString()) - .Returns("Hello"); - myMock.Reset(); - myMock.VerifyAll(); - } + [Fact] + public void LooseNoCall() + { + var myMock = new Mock>(MockBehavior.Loose); + myMock + .Setup(a => a.ToString()) + .Returns("Hello"); + myMock.Reset(); + myMock.VerifyAll(); + } - [Fact] - - public void StrictNoCall() - { - var myMock = new Mock>(MockBehavior.Strict); - myMock - .Setup(a => a.ToString()) - .Returns("Hello"); - myMock.Reset(); - myMock.VerifyAll(); - } - #endregion - } + [Fact] + public void StrictNoCall() + { + var myMock = new Mock>(MockBehavior.Strict); + myMock + .Setup(a => a.ToString()) + .Returns("Hello"); + myMock.Reset(); + myMock.VerifyAll(); + } + #endregion + } - public interface IFooReset - { - #region Public Methods + public interface IFooReset + { + #region Public Methods - object Execute(string ping); + object Execute(string ping); - #endregion - } + #endregion + } } diff --git a/UnitTests/GeneratedReturnsExtensionsFixture.cs b/UnitTests/GeneratedReturnsExtensionsFixture.cs index 24cb4ee0c..ff014772c 100644 --- a/UnitTests/GeneratedReturnsExtensionsFixture.cs +++ b/UnitTests/GeneratedReturnsExtensionsFixture.cs @@ -5,91 +5,91 @@ namespace Moq.Tests { - public class GeneratedReturnsExtensionsFixture - { - public interface IAsyncInterface - { - Task WithSingleParameterAsync(int parameter); - Task WithMultiParameterAsync(string firstParameter, string secondParameter); - Task WithParamsAsync(params DateTime[] dateTimes); - } - - [Fact] - public void ReturnsAsync_onSingleParameter_ParameterUsedForCalculationOfTheResult() - { - var mock = new Mock(); - mock.Setup(x => x.WithSingleParameterAsync(It.IsAny())).ReturnsAsync((int x) => x * x); - - int evaluationResult = mock.Object.WithSingleParameterAsync(2).Result; - - Assert.Equal(4, evaluationResult); - } - - [Fact] - public void ReturnsAsync_onSingleParameter_LazyEvaluationOfTheResult() - { - int coefficient = 5; - var mock = new Mock(); - mock.Setup(x => x.WithSingleParameterAsync(It.IsAny())).ReturnsAsync((int x) => x * coefficient); - - int firstEvaluationResult = mock.Object.WithSingleParameterAsync(2).Result; - - coefficient = 10; - int secondEvaluationResult = mock.Object.WithSingleParameterAsync(2).Result; - - Assert.NotEqual(firstEvaluationResult, secondEvaluationResult); - } - - [Fact] - public void ReturnsAsync_onMultiParameter_ParametersUsedForCalculationOfTheResult() - { - var mock = new Mock(); - mock.Setup(x => x.WithMultiParameterAsync(It.IsAny(), It.IsAny())).ReturnsAsync((string first, string second) => first + second); - - string evaluationResult = mock.Object.WithMultiParameterAsync("Moq", "4").Result; - - Assert.Equal("Moq4", evaluationResult); - } - - [Fact] - public void ReturnsAsync_onMultiParameter_LazyEvaluationOfTheResult() - { - var mock = new Mock(); - mock.Setup(x => x.WithMultiParameterAsync(It.IsAny(), It.IsAny())).ReturnsAsync((string first, string second) => first + second); - - string firstEvaluationResult = mock.Object.WithMultiParameterAsync("Moq", "4").Result; - string secondEvaluationResult = mock.Object.WithMultiParameterAsync("Moq", "4").Result; - - Assert.NotSame(firstEvaluationResult, secondEvaluationResult); - } - - [Fact] - public void ReturnsAsync_onParams_AllParametersUsedForCalculationOfTheResult() - { - var mock = new Mock(); - mock.Setup(x => x.WithParamsAsync(It.IsAny())) - .ReturnsAsync((DateTime[] dateTimes) => dateTimes.Max()); - - DateTime evaluationResult = mock.Object.WithParamsAsync(DateTime.MinValue, DateTime.Now, DateTime.MaxValue).Result; - - Assert.Equal(DateTime.MaxValue, evaluationResult); - } - - [Fact] - public void ReturnsAsync_onParams_LazyEvaluationOfTheResult() - { - DateTime comparedDateTime = DateTime.MinValue; - var mock = new Mock(); - mock.Setup(x => x.WithParamsAsync(It.IsAny())) - .ReturnsAsync((DateTime[] dateTimes) => dateTimes.Concat(new[] { comparedDateTime }).Max()); - - DateTime now = DateTime.Now; - DateTime firstEvaluationResult = mock.Object.WithParamsAsync(DateTime.MinValue, now).Result; - - comparedDateTime = DateTime.MaxValue; - DateTime secondEvaluationResult = mock.Object.WithParamsAsync(DateTime.MinValue, now).Result; - - Assert.NotEqual(firstEvaluationResult, secondEvaluationResult); - } - } -} \ No newline at end of file + public class GeneratedReturnsExtensionsFixture + { + public interface IAsyncInterface + { + Task WithSingleParameterAsync(int parameter); + Task WithMultiParameterAsync(string firstParameter, string secondParameter); + Task WithParamsAsync(params DateTime[] dateTimes); + } + + [Fact] + public void ReturnsAsync_onSingleParameter_ParameterUsedForCalculationOfTheResult() + { + var mock = new Mock(); + mock.Setup(x => x.WithSingleParameterAsync(It.IsAny())).ReturnsAsync((int x) => x * x); + + int evaluationResult = mock.Object.WithSingleParameterAsync(2).Result; + + Assert.Equal(4, evaluationResult); + } + + [Fact] + public void ReturnsAsync_onSingleParameter_LazyEvaluationOfTheResult() + { + int coefficient = 5; + var mock = new Mock(); + mock.Setup(x => x.WithSingleParameterAsync(It.IsAny())).ReturnsAsync((int x) => x * coefficient); + + int firstEvaluationResult = mock.Object.WithSingleParameterAsync(2).Result; + + coefficient = 10; + int secondEvaluationResult = mock.Object.WithSingleParameterAsync(2).Result; + + Assert.NotEqual(firstEvaluationResult, secondEvaluationResult); + } + + [Fact] + public void ReturnsAsync_onMultiParameter_ParametersUsedForCalculationOfTheResult() + { + var mock = new Mock(); + mock.Setup(x => x.WithMultiParameterAsync(It.IsAny(), It.IsAny())).ReturnsAsync((string first, string second) => first + second); + + string evaluationResult = mock.Object.WithMultiParameterAsync("Moq", "4").Result; + + Assert.Equal("Moq4", evaluationResult); + } + + [Fact] + public void ReturnsAsync_onMultiParameter_LazyEvaluationOfTheResult() + { + var mock = new Mock(); + mock.Setup(x => x.WithMultiParameterAsync(It.IsAny(), It.IsAny())).ReturnsAsync((string first, string second) => first + second); + + string firstEvaluationResult = mock.Object.WithMultiParameterAsync("Moq", "4").Result; + string secondEvaluationResult = mock.Object.WithMultiParameterAsync("Moq", "4").Result; + + Assert.NotSame(firstEvaluationResult, secondEvaluationResult); + } + + [Fact] + public void ReturnsAsync_onParams_AllParametersUsedForCalculationOfTheResult() + { + var mock = new Mock(); + mock.Setup(x => x.WithParamsAsync(It.IsAny())) + .ReturnsAsync((DateTime[] dateTimes) => dateTimes.Max()); + + DateTime evaluationResult = mock.Object.WithParamsAsync(DateTime.MinValue, DateTime.Now, DateTime.MaxValue).Result; + + Assert.Equal(DateTime.MaxValue, evaluationResult); + } + + [Fact] + public void ReturnsAsync_onParams_LazyEvaluationOfTheResult() + { + DateTime comparedDateTime = DateTime.MinValue; + var mock = new Mock(); + mock.Setup(x => x.WithParamsAsync(It.IsAny())) + .ReturnsAsync((DateTime[] dateTimes) => dateTimes.Concat(new[] { comparedDateTime }).Max()); + + DateTime now = DateTime.Now; + DateTime firstEvaluationResult = mock.Object.WithParamsAsync(DateTime.MinValue, now).Result; + + comparedDateTime = DateTime.MaxValue; + DateTime secondEvaluationResult = mock.Object.WithParamsAsync(DateTime.MinValue, now).Result; + + Assert.NotEqual(firstEvaluationResult, secondEvaluationResult); + } + } +} diff --git a/UnitTests/Library/ClassLibrary1/ClassLibrary1.NetCore.csproj b/UnitTests/Library/ClassLibrary1/ClassLibrary1.NetCore.csproj index d68313b0d..1fa8b77f4 100644 --- a/UnitTests/Library/ClassLibrary1/ClassLibrary1.NetCore.csproj +++ b/UnitTests/Library/ClassLibrary1/ClassLibrary1.NetCore.csproj @@ -1,21 +1,21 @@  - - netstandard1.3 - ClassLibrary1 - Foo.snk - true - true - ClassLibrary1 - false - + + netstandard1.3 + ClassLibrary1 + Foo.snk + true + true + ClassLibrary1 + false + - - $(DefineConstants);NETCORE - + + $(DefineConstants);NETCORE + - - - + + + diff --git a/UnitTests/Library/ClassLibrary1/ClassLibrary1.csproj b/UnitTests/Library/ClassLibrary1/ClassLibrary1.csproj index 4c918863b..1b0ce8664 100644 --- a/UnitTests/Library/ClassLibrary1/ClassLibrary1.csproj +++ b/UnitTests/Library/ClassLibrary1/ClassLibrary1.csproj @@ -1,61 +1,61 @@  - - Debug - AnyCPU - 8.0.30703 - 2.0 - {AD73DEAC-E669-4070-BE05-099F9F313007} - Library - Properties - ClassLibrary1 - ClassLibrary1 - v3.5 - 512 + + Debug + AnyCPU + 8.0.30703 + 2.0 + {AD73DEAC-E669-4070-BE05-099F9F313007} + Library + Properties + ClassLibrary1 + ClassLibrary1 + v3.5 + 512 $([MSBuild]::GetDirectoryNameOfFileAbove($(MSBuildThisFileDirectory), Moq.Tests.csproj))\ - - true - full - false - DEBUG;TRACE - prompt - 4 - - - pdbonly - true - TRACE - prompt - 4 - - - true - - - Foo.snk - - - - - - - - - - - - - - - - - - + + true + full + false + DEBUG;TRACE + prompt + 4 + + + pdbonly + true + TRACE + prompt + 4 + + + true + + + Foo.snk + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/UnitTests/Library/ClassLibrary2/ClassLibrary2.NetCore.csproj b/UnitTests/Library/ClassLibrary2/ClassLibrary2.NetCore.csproj index 57044d845..f40f533fb 100644 --- a/UnitTests/Library/ClassLibrary2/ClassLibrary2.NetCore.csproj +++ b/UnitTests/Library/ClassLibrary2/ClassLibrary2.NetCore.csproj @@ -1,22 +1,22 @@  - - 2.0.0 - netstandard1.3 - ClassLibrary2 - Bar.snk - true - true - ClassLibrary2 - false - + + 2.0.0 + netstandard1.3 + ClassLibrary2 + Bar.snk + true + true + ClassLibrary2 + false + - - - + + + - - $(DefineConstants);NETCORE - + + $(DefineConstants);NETCORE + diff --git a/UnitTests/Library/ClassLibrary2/ClassLibrary2.csproj b/UnitTests/Library/ClassLibrary2/ClassLibrary2.csproj index e086aeaca..9e69ca302 100644 --- a/UnitTests/Library/ClassLibrary2/ClassLibrary2.csproj +++ b/UnitTests/Library/ClassLibrary2/ClassLibrary2.csproj @@ -1,67 +1,67 @@  - - Debug - AnyCPU - 8.0.30703 - 2.0 - {F16C2503-9FBB-464D-AFF0-E58E97769B9E} - Library - Properties - ClassLibrary2 - ClassLibrary2 - v3.5 - 512 + + Debug + AnyCPU + 8.0.30703 + 2.0 + {F16C2503-9FBB-464D-AFF0-E58E97769B9E} + Library + Properties + ClassLibrary2 + ClassLibrary2 + v3.5 + 512 $([MSBuild]::GetDirectoryNameOfFileAbove($(MSBuildThisFileDirectory), Moq.Tests.csproj))\ - - true - full - false - DEBUG;TRACE - prompt - 4 - - - pdbonly - true - TRACE - prompt - 4 - - - true - - - Bar.snk - - - - - - - - - - - - - - - - - - - {AD73DEAC-E669-4070-BE05-099F9F313007} - ClassLibrary1 - - - - + + true + full + false + DEBUG;TRACE + prompt + 4 + + + pdbonly + true + TRACE + prompt + 4 + + + true + + + Bar.snk + + + + + + + + + + + + + + + + + + + {AD73DEAC-E669-4070-BE05-099F9F313007} + ClassLibrary1 + + + + \ No newline at end of file diff --git a/UnitTests/Linq/QueryableMocksFixture.cs b/UnitTests/Linq/QueryableMocksFixture.cs index 75b3b64fd..0ec6c639c 100644 --- a/UnitTests/Linq/QueryableMocksFixture.cs +++ b/UnitTests/Linq/QueryableMocksFixture.cs @@ -125,21 +125,21 @@ public void ShouldSupportSettingDtoPropertyValue() Assert.Equal("foo", target.Value); } - [Fact] - public void ShouldSupportSettingDtoProtectedPropertyValue() - { - var target = Mock.Of(x => x.ProtectedValue == "foo"); + [Fact] + public void ShouldSupportSettingDtoProtectedPropertyValue() + { + var target = Mock.Of(x => x.ProtectedValue == "foo"); - Assert.Equal("foo", target.ProtectedValue); - } + Assert.Equal("foo", target.ProtectedValue); + } - [Fact] - public void ShouldSupportSettingDtoProtectedVirtualPropertyValue() - { - var target = Mock.Of(x => x.ProtectedVirtualValue == "foo"); + [Fact] + public void ShouldSupportSettingDtoProtectedVirtualPropertyValue() + { + var target = Mock.Of(x => x.ProtectedVirtualValue == "foo"); - Assert.Equal("foo", target.ProtectedVirtualValue); - } + Assert.Equal("foo", target.ProtectedVirtualValue); + } [Fact] public void ShouldOneOfCreateNewMock() @@ -217,37 +217,37 @@ public interface IBaz } } - public class Foo - { - protected Foo() - { - } - - public virtual string Value { get; private set; } - } - - public class FooFixture - { - [Fact] - public void Test() - { - var remote = Mock.Of(rt => rt.Value == "foo"); - Assert.Equal("foo", remote.Value); - } - } - - public interface IBar - { - Foo Foo { get; set; } - } - - public class BarFixture - { - [Fact] - public void Test() - { - var remote = Mock.Of(rt => rt.Foo.Value == "foo"); - Assert.Equal("foo", remote.Foo.Value); - } - } + public class Foo + { + protected Foo() + { + } + + public virtual string Value { get; private set; } + } + + public class FooFixture + { + [Fact] + public void Test() + { + var remote = Mock.Of(rt => rt.Value == "foo"); + Assert.Equal("foo", remote.Value); + } + } + + public interface IBar + { + Foo Foo { get; set; } + } + + public class BarFixture + { + [Fact] + public void Test() + { + var remote = Mock.Of(rt => rt.Foo.Value == "foo"); + Assert.Equal("foo", remote.Foo.Value); + } + } } diff --git a/UnitTests/Linq/SupportedQuerying.cs b/UnitTests/Linq/SupportedQuerying.cs index ad37cc902..a6027888a 100644 --- a/UnitTests/Linq/SupportedQuerying.cs +++ b/UnitTests/Linq/SupportedQuerying.cs @@ -280,4 +280,4 @@ public class Foo } } } -} \ No newline at end of file +} diff --git a/UnitTests/Linq/UnsupportedQuerying.cs b/UnitTests/Linq/UnsupportedQuerying.cs index ebfbe47a9..00736eef4 100644 --- a/UnitTests/Linq/UnsupportedQuerying.cs +++ b/UnitTests/Linq/UnsupportedQuerying.cs @@ -203,4 +203,4 @@ public interface IFoo } } } -} \ No newline at end of file +} diff --git a/UnitTests/MatchersFixture.cs b/UnitTests/MatchersFixture.cs index dacbe869c..79dd7537b 100644 --- a/UnitTests/MatchersFixture.cs +++ b/UnitTests/MatchersFixture.cs @@ -58,69 +58,69 @@ public void MatchesRanges() Assert.Equal(2, mock.Object.Echo(9)); } - [Fact] - public void MatchesIsInEnumerable() - { - var mock = new Mock(); + [Fact] + public void MatchesIsInEnumerable() + { + var mock = new Mock(); - mock.Setup(x => x.Echo(It.IsIn(Enumerable.Range(1, 5)))).Returns(1); - mock.Setup(x => x.Echo(It.IsIn(Enumerable.Range(6, 10)))).Returns(2); + mock.Setup(x => x.Echo(It.IsIn(Enumerable.Range(1, 5)))).Returns(1); + mock.Setup(x => x.Echo(It.IsIn(Enumerable.Range(6, 10)))).Returns(2); - Assert.Equal(1, mock.Object.Echo(1)); - Assert.Equal(1, mock.Object.Echo(2)); - Assert.Equal(1, mock.Object.Echo(5)); + Assert.Equal(1, mock.Object.Echo(1)); + Assert.Equal(1, mock.Object.Echo(2)); + Assert.Equal(1, mock.Object.Echo(5)); - Assert.Equal(2, mock.Object.Echo(7)); - Assert.Equal(2, mock.Object.Echo(9)); - } + Assert.Equal(2, mock.Object.Echo(7)); + Assert.Equal(2, mock.Object.Echo(9)); + } - [Fact] - public void MatchesIsInVariadicParameters() - { - var mock = new Mock(); + [Fact] + public void MatchesIsInVariadicParameters() + { + var mock = new Mock(); - mock.Setup(x => x.Echo(It.IsIn(1, 2, 3, 4, 5))).Returns(1); - mock.Setup(x => x.Echo(It.IsIn(6, 7, 8, 9, 10))).Returns(2); + mock.Setup(x => x.Echo(It.IsIn(1, 2, 3, 4, 5))).Returns(1); + mock.Setup(x => x.Echo(It.IsIn(6, 7, 8, 9, 10))).Returns(2); - Assert.Equal(1, mock.Object.Echo(1)); - Assert.Equal(1, mock.Object.Echo(2)); - Assert.Equal(1, mock.Object.Echo(5)); + Assert.Equal(1, mock.Object.Echo(1)); + Assert.Equal(1, mock.Object.Echo(2)); + Assert.Equal(1, mock.Object.Echo(5)); - Assert.Equal(2, mock.Object.Echo(7)); - Assert.Equal(2, mock.Object.Echo(9)); - } + Assert.Equal(2, mock.Object.Echo(7)); + Assert.Equal(2, mock.Object.Echo(9)); + } - [Fact] - public void MatchesIsNotInEnumerable() - { - var mock = new Mock(); + [Fact] + public void MatchesIsNotInEnumerable() + { + var mock = new Mock(); - mock.Setup(x => x.Echo(It.IsNotIn(Enumerable.Range(1, 5)))).Returns(1); - mock.Setup(x => x.Echo(It.IsNotIn(Enumerable.Range(6, 10)))).Returns(2); + mock.Setup(x => x.Echo(It.IsNotIn(Enumerable.Range(1, 5)))).Returns(1); + mock.Setup(x => x.Echo(It.IsNotIn(Enumerable.Range(6, 10)))).Returns(2); - Assert.Equal(2, mock.Object.Echo(1)); - Assert.Equal(2, mock.Object.Echo(2)); - Assert.Equal(2, mock.Object.Echo(5)); + Assert.Equal(2, mock.Object.Echo(1)); + Assert.Equal(2, mock.Object.Echo(2)); + Assert.Equal(2, mock.Object.Echo(5)); - Assert.Equal(1, mock.Object.Echo(7)); - Assert.Equal(1, mock.Object.Echo(9)); - } + Assert.Equal(1, mock.Object.Echo(7)); + Assert.Equal(1, mock.Object.Echo(9)); + } - [Fact] - public void MatchesIsNotInVariadicParameters() - { - var mock = new Mock(); + [Fact] + public void MatchesIsNotInVariadicParameters() + { + var mock = new Mock(); - mock.Setup(x => x.Echo(It.IsNotIn(1, 2, 3, 4, 5))).Returns(1); - mock.Setup(x => x.Echo(It.IsNotIn(6, 7, 8, 9, 10))).Returns(2); + mock.Setup(x => x.Echo(It.IsNotIn(1, 2, 3, 4, 5))).Returns(1); + mock.Setup(x => x.Echo(It.IsNotIn(6, 7, 8, 9, 10))).Returns(2); - Assert.Equal(2, mock.Object.Echo(1)); - Assert.Equal(2, mock.Object.Echo(2)); - Assert.Equal(2, mock.Object.Echo(5)); + Assert.Equal(2, mock.Object.Echo(1)); + Assert.Equal(2, mock.Object.Echo(2)); + Assert.Equal(2, mock.Object.Echo(5)); - Assert.Equal(1, mock.Object.Echo(7)); - Assert.Equal(1, mock.Object.Echo(9)); - } + Assert.Equal(1, mock.Object.Echo(7)); + Assert.Equal(1, mock.Object.Echo(9)); + } [Fact] public void DoesNotMatchOutOfRange() @@ -266,20 +266,20 @@ public void MatchingNonNullableValueTypeForNullableParameterDoesNotMatchNull() Assert.Equal(0, mock.Object.TakesNullableParameter(null)); } - [Fact] - public void MultipleMatchingSetupsWithMultiplValueTypeArgumentsReplaceEachOtherForVerify() - { - var mock = new Mock(); + [Fact] + public void MultipleMatchingSetupsWithMultiplValueTypeArgumentsReplaceEachOtherForVerify() + { + var mock = new Mock(); + + mock.Setup(x => x.TakesTwoValueTypes(1, 2)).Verifiable(); + mock.Setup(x => x.TakesTwoValueTypes(1, 2)).Verifiable(); - mock.Setup(x => x.TakesTwoValueTypes(1, 2)).Verifiable(); - mock.Setup(x => x.TakesTwoValueTypes(1, 2)).Verifiable(); + mock.Object.TakesTwoValueTypes(1, 2); - mock.Object.TakesTwoValueTypes(1, 2); + mock.Verify(); + } - mock.Verify(); - } - - private int GetToRange() + private int GetToRange() { return 5; } @@ -296,7 +296,7 @@ public interface IFoo int DoAddition(int[] numbers); int[] Items { get; set; } int TakesNullableParameter(int? value); - void TakesTwoValueTypes(int a, int b); - } + void TakesTwoValueTypes(int a, int b); + } } } diff --git a/UnitTests/MockSequenceFixture.cs b/UnitTests/MockSequenceFixture.cs index dba608492..75f5c3c6f 100644 --- a/UnitTests/MockSequenceFixture.cs +++ b/UnitTests/MockSequenceFixture.cs @@ -117,4 +117,4 @@ public interface IFoo int Do(int arg); } } -} \ No newline at end of file +} diff --git a/UnitTests/MockedEventsFixture.cs b/UnitTests/MockedEventsFixture.cs index 80c42f69d..b134d29ae 100644 --- a/UnitTests/MockedEventsFixture.cs +++ b/UnitTests/MockedEventsFixture.cs @@ -704,6 +704,5 @@ public class FordawrdEventDoProtectedImplementation : INotifyPropertyChanged } } } - } } diff --git a/UnitTests/MockedFixture.cs b/UnitTests/MockedFixture.cs index 6fba64576..196fec36a 100644 --- a/UnitTests/MockedFixture.cs +++ b/UnitTests/MockedFixture.cs @@ -92,4 +92,4 @@ public interface IFoo { } } -} \ No newline at end of file +} diff --git a/UnitTests/Moq.NetCore.Tests.csproj b/UnitTests/Moq.NetCore.Tests.csproj index fe3c47f99..6b96b8269 100644 --- a/UnitTests/Moq.NetCore.Tests.csproj +++ b/UnitTests/Moq.NetCore.Tests.csproj @@ -1,46 +1,46 @@  - - Moq.NetCore.UnitTests Class Library - netcoreapp1.0 - Moq.NetCore.Tests - ../Moq.snk - true - true - Moq.NetCore.Tests - true - - - - - - - - - - - - - - - - $(DefineConstants);NETCORE - - - - - - - - - - - - - - - - - + + Moq.NetCore.UnitTests Class Library + netcoreapp1.0 + Moq.NetCore.Tests + ../Moq.snk + true + true + Moq.NetCore.Tests + true + + + + + + + + + + + + + + + + $(DefineConstants);NETCORE + + + + + + + + + + + + + + + + + diff --git a/UnitTests/Moq.Tests.csproj b/UnitTests/Moq.Tests.csproj index 06931e800..85fcd7946 100644 --- a/UnitTests/Moq.Tests.csproj +++ b/UnitTests/Moq.Tests.csproj @@ -1,115 +1,115 @@  - - Debug - AnyCPU - 9.0.30729 - 2.0 - {81BBC911-4916-4E10-A955-752AE47CB2B9} - Library - Properties - Moq.Tests - Moq.Tests - v4.5 - 512 - true - ..\Moq.snk - - ..\ - true - - - true - full - false - bin\Debug\ - TRACE;DEBUG;DESKTOP - prompt - 4 - AllRules.ruleset - - - full - true - bin\Release\ - TRACE;DESKTOP - prompt - 4 - true - AllRules.ruleset - - - - .\ClassLibrary1.dll - - - .\ClassLibrary2.dll - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - Moq.snk - - - - - - {1C91AC30-5977-4BE5-BA67-8EB186C03514} - Moq - - - - - - - \ No newline at end of file + + Debug + AnyCPU + 9.0.30729 + 2.0 + {81BBC911-4916-4E10-A955-752AE47CB2B9} + Library + Properties + Moq.Tests + Moq.Tests + v4.5 + 512 + true + ..\Moq.snk + + ..\ + true + + + true + full + false + bin\Debug\ + TRACE;DEBUG;DESKTOP + prompt + 4 + AllRules.ruleset + + + full + true + bin\Release\ + TRACE;DESKTOP + prompt + 4 + true + AllRules.ruleset + + + + .\ClassLibrary1.dll + + + .\ClassLibrary2.dll + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Moq.snk + + + + + + {1C91AC30-5977-4BE5-BA67-8EB186C03514} + Moq + + + + + + + diff --git a/UnitTests/OccurrenceFixture.cs b/UnitTests/OccurrenceFixture.cs index 64f44fce6..eb4f67bb0 100644 --- a/UnitTests/OccurrenceFixture.cs +++ b/UnitTests/OccurrenceFixture.cs @@ -53,4 +53,4 @@ public interface IFoo string Execute(string command); } } -} \ No newline at end of file +} diff --git a/UnitTests/Pex/Moq.UnitTests.Pex.csproj b/UnitTests/Pex/Moq.UnitTests.Pex.csproj index e31e2a883..56163233b 100644 --- a/UnitTests/Pex/Moq.UnitTests.Pex.csproj +++ b/UnitTests/Pex/Moq.UnitTests.Pex.csproj @@ -1,68 +1,68 @@  - - Debug - AnyCPU - 9.0.30729 - 2.0 - {662DD403-EFFD-4804-A29D-2E1F80D92835} - Library - Properties - Moq.UnitTests.Pex - Moq.UnitTests.Pex - v3.5 - 512 - - - true - full - false - bin\Debug\ - DEBUG;TRACE - prompt - 4 - - - pdbonly - true - bin\Release\ - TRACE - prompt - 4 - - - - False - C:\Program Files (x86)\Microsoft Pex\bin\Microsoft.Pex.Framework.dll - - - - - 3.5 - - - - - - - - - - - - {1C91AC30-5977-4BE5-BA67-8EB186C03514} - Moq - - - - - - - + + Debug + AnyCPU + 9.0.30729 + 2.0 + {662DD403-EFFD-4804-A29D-2E1F80D92835} + Library + Properties + Moq.UnitTests.Pex + Moq.UnitTests.Pex + v3.5 + 512 + + + true + full + false + bin\Debug\ + DEBUG;TRACE + prompt + 4 + + + pdbonly + true + bin\Release\ + TRACE + prompt + 4 + + + + False + C:\Program Files (x86)\Microsoft Pex\bin\Microsoft.Pex.Framework.dll + + + + + 3.5 + + + + + + + + + + + + {1C91AC30-5977-4BE5-BA67-8EB186C03514} + Moq + + + + + + + \ No newline at end of file diff --git a/UnitTests/Pex/ShouldExpectCallReturn.cs b/UnitTests/Pex/ShouldExpectCallReturn.cs index 0c4098ee2..8c499bc0c 100644 --- a/UnitTests/Pex/ShouldExpectCallReturn.cs +++ b/UnitTests/Pex/ShouldExpectCallReturn.cs @@ -16,21 +16,21 @@ namespace Mock.Tests { - [TestClass] - [PexClass(Suite = "checkin")] - public partial class ShouldExpectCallReturn - { - [TestMethod] - [PexMethod(MaxBranches = int.MaxValue)] - public void Moq() - { - // ShouldExpectCallReturn - var mock = new Mock(); - var clone = new object(); + [TestClass] + [PexClass(Suite = "checkin")] + public partial class ShouldExpectCallReturn + { + [TestMethod] + [PexMethod(MaxBranches = int.MaxValue)] + public void Moq() + { + // ShouldExpectCallReturn + var mock = new Mock(); + var clone = new object(); - mock.Setup(x => x.Clone()).Returns(clone); + mock.Setup(x => x.Clone()).Returns(clone); - Assert.AreSame(clone, mock.Object.Clone()); - } - } + Assert.AreSame(clone, mock.Object.Clone()); + } + } } diff --git a/UnitTests/Pex/ShouldExpectCallWithArgument.cs b/UnitTests/Pex/ShouldExpectCallWithArgument.cs index 2b82fca1f..05b6bbe3e 100644 --- a/UnitTests/Pex/ShouldExpectCallWithArgument.cs +++ b/UnitTests/Pex/ShouldExpectCallWithArgument.cs @@ -81,4 +81,4 @@ public void MoqWithSymbolicArgumentParameterValue(int y, int z) throw new PexGoalException(); } } -} \ No newline at end of file +} diff --git a/UnitTests/Pex/ShouldExpectCallWithReferenceLazyEvaluate.cs b/UnitTests/Pex/ShouldExpectCallWithReferenceLazyEvaluate.cs index 5ed049a9d..03808e70f 100644 --- a/UnitTests/Pex/ShouldExpectCallWithReferenceLazyEvaluate.cs +++ b/UnitTests/Pex/ShouldExpectCallWithReferenceLazyEvaluate.cs @@ -16,24 +16,24 @@ namespace Mock.Tests { - [TestClass] - [PexClass(Suite = "checkin")] - public partial class ShouldExpectCallWithReferenceLazyEvaluate - { - public interface IFoo - { - int Parse(string value); - } + [TestClass] + [PexClass(Suite = "checkin")] + public partial class ShouldExpectCallWithReferenceLazyEvaluate + { + public interface IFoo + { + int Parse(string value); + } - [PexMethod(MaxBranches = int.MaxValue)] - public void Moq() - { - int a = 25; - var mock = new Mock(); - mock.Setup(x => x.Parse(a.ToString())).Returns(() => a); + [PexMethod(MaxBranches = int.MaxValue)] + public void Moq() + { + int a = 25; + var mock = new Mock(); + mock.Setup(x => x.Parse(a.ToString())).Returns(() => a); - a = 10; - Assert.AreEqual(10, mock.Object.Parse("10")); - } - } + a = 10; + Assert.AreEqual(10, mock.Object.Parse("10")); + } + } } diff --git a/UnitTests/Pex/ShouldExpectReturnPropertyValue.cs b/UnitTests/Pex/ShouldExpectReturnPropertyValue.cs index e1a86a239..fbda74f95 100644 --- a/UnitTests/Pex/ShouldExpectReturnPropertyValue.cs +++ b/UnitTests/Pex/ShouldExpectReturnPropertyValue.cs @@ -16,21 +16,21 @@ namespace Mock.Tests { - [TestClass] - [PexClass(Suite = "checkin")] - public partial class ShouldExpectReturnPropertyValue - { - public interface IFoo - { - int ValueProperty { get; } - } + [TestClass] + [PexClass(Suite = "checkin")] + public partial class ShouldExpectReturnPropertyValue + { + public interface IFoo + { + int ValueProperty { get; } + } - [PexMethod(MaxBranches = int.MaxValue)] - public void Moq() - { - var mock = new Mock(); - mock.Setup(x => x.ValueProperty).Returns(25); - Assert.AreEqual(25, mock.Object.ValueProperty); - } - } + [PexMethod(MaxBranches = int.MaxValue)] + public void Moq() + { + var mock = new Mock(); + mock.Setup(x => x.ValueProperty).Returns(25); + Assert.AreEqual(25, mock.Object.ValueProperty); + } + } } diff --git a/UnitTests/Pex/ShouldMatchPredicateArgument.cs b/UnitTests/Pex/ShouldMatchPredicateArgument.cs index 6ccfb118d..639416cea 100644 --- a/UnitTests/Pex/ShouldMatchPredicateArgument.cs +++ b/UnitTests/Pex/ShouldMatchPredicateArgument.cs @@ -15,26 +15,26 @@ namespace Mock.Tests { - [TestClass] - [PexClass(Suite = "checkin")] - public partial class ShouldMatchPredicateArgument - { - public interface IFoo - { - int Duplicate(int i); - } + [TestClass] + [PexClass(Suite = "checkin")] + public partial class ShouldMatchPredicateArgument + { + public interface IFoo + { + int Duplicate(int i); + } - [TestMethod] - [PexMethod(MaxBranches = int.MaxValue)] - public void Moq() - { - var mock = new Mock(); + [TestMethod] + [PexMethod(MaxBranches = int.MaxValue)] + public void Moq() + { + var mock = new Mock(); - mock.Setup(x => x.Duplicate(It.Is(value => value < 5 && value > 0))) - .Returns(() => 1); + mock.Setup(x => x.Duplicate(It.Is(value => value < 5 && value > 0))) + .Returns(() => 1); - Assert.AreEqual(1, mock.Object.Duplicate(3)); - Assert.AreEqual(0, mock.Object.Duplicate(0)); - } - } + Assert.AreEqual(1, mock.Object.Duplicate(3)); + Assert.AreEqual(0, mock.Object.Duplicate(0)); + } + } } diff --git a/UnitTests/ProtectedMockFixture.cs b/UnitTests/ProtectedMockFixture.cs index 373b02d72..e61d99dc0 100644 --- a/UnitTests/ProtectedMockFixture.cs +++ b/UnitTests/ProtectedMockFixture.cs @@ -904,4 +904,4 @@ public class MyBase { } public class MyDerived : MyBase { } } -} \ No newline at end of file +} diff --git a/UnitTests/Regressions/IssueReportsFixture.cs b/UnitTests/Regressions/IssueReportsFixture.cs index d66752897..d6e40cb0a 100644 --- a/UnitTests/Regressions/IssueReportsFixture.cs +++ b/UnitTests/Regressions/IssueReportsFixture.cs @@ -24,60 +24,60 @@ // NOTE class without namespace public class _181 { - [Fact] - public void ReproTest() - { - var mock = new Mock(); - mock.Object.Dispose(); - - mock.Verify(d => d.Dispose()); - } + [Fact] + public void ReproTest() + { + var mock = new Mock(); + mock.Object.Dispose(); + + mock.Verify(d => d.Dispose()); + } } #endregion namespace Moq.Tests.Regressions { - public class IssueReportsFixture - { - // @ GitHub + public class IssueReportsFixture + { + // @ GitHub - #region #54 + #region #54 - public class Issue54 - { - public interface IFoo - { - void Bar(); - } + public class Issue54 + { + public interface IFoo + { + void Bar(); + } - [Fact] - public void when_as_disposable_then_succeeds() - { - var mock = new Mock(); - mock.Setup(x => x.Bar()); - mock.As().Setup(x => x.Dispose()); + [Fact] + public void when_as_disposable_then_succeeds() + { + var mock = new Mock(); + mock.Setup(x => x.Bar()); + mock.As().Setup(x => x.Dispose()); - Action testMock = (IFoo foo) => - { - foo.Bar(); + Action testMock = (IFoo foo) => + { + foo.Bar(); - var disposable = foo as IDisposable; + var disposable = foo as IDisposable; - if (disposable != null) - { - disposable.Dispose(); - } - }; + if (disposable != null) + { + disposable.Dispose(); + } + }; - testMock(mock.Object); + testMock(mock.Object); - mock.VerifyAll(); - } - } + mock.VerifyAll(); + } + } - #endregion + #endregion #region 47 & 62 @@ -129,11 +129,9 @@ public interface IIssue78Interface public class Issue78TypeOne { - } public class Issue78TypeTwo { - } public class Issue78Sut @@ -228,7 +226,7 @@ public void when_a_method_doesnt_have_generic_parameters_exception_doesnt_includ #endregion // #176 - #region #184 + #region #184 public class Issue184 { @@ -247,36 +245,36 @@ public void strict_mock_accepts_null_as_nullable_guid_value() } } - #endregion // #184 + #endregion // #184 + + #region #252 - #region #252 + public class Issue252 + { + [Fact] + public void SetupsWithSameArgumentsInDifferentOrderShouldNotOverwriteEachOther() + { + var mock = new Mock(); - public class Issue252 - { - [Fact] - public void SetupsWithSameArgumentsInDifferentOrderShouldNotOverwriteEachOther() - { - var mock = new Mock(); + var a = new MyClass(); + var b = new MyClass(); - var a = new MyClass(); - var b = new MyClass(); - - mock.Setup(m => m.Method(a, b)).Returns(1); - mock.Setup(m => m.Method(b, a)).Returns(2); + mock.Setup(m => m.Method(a, b)).Returns(1); + mock.Setup(m => m.Method(b, a)).Returns(2); - Assert.Equal(1, mock.Object.Method(a, b)); - Assert.Equal(2, mock.Object.Method(b, a)); - } + Assert.Equal(1, mock.Object.Method(a, b)); + Assert.Equal(2, mock.Object.Method(b, a)); + } - public interface ISimpleInterface - { - int Method(MyClass a, MyClass b); - } + public interface ISimpleInterface + { + int Method(MyClass a, MyClass b); + } - public class MyClass { } - } + public class MyClass { } + } - #endregion // #252 + #endregion // #252 #region #273 @@ -303,1825 +301,1825 @@ public interface IMyInterface #endregion // #252 - #region 311 - - public sealed class Issue311 - { - [Fact] - public void Can_still_provide_default_value_for_vector() - { - var mocked = Mock.Of(); - - var vector = mocked.Vector; - Assert.NotNull(vector); - Assert.True(vector.GetType().IsArray); - Assert.Equal(1, vector.GetType().GetArrayRank()); - } - - [Fact] - public void Can_provide_default_value_for_twodimensional_array_property() - { - var mocked = Mock.Of(); - - var twoDimensionalArray = mocked.TwoDimensionalArray; - Assert.NotNull(twoDimensionalArray); - Assert.True(twoDimensionalArray.GetType().IsArray); - Assert.Equal(2, twoDimensionalArray.GetType().GetArrayRank()); - } - - [Fact] - public void Can_provide_default_value_for_threedimensional_arrays() - { - var mocked = Mock.Of(); - - var threeDimensionalArray = mocked.ThreeDimensionalArray; - Assert.NotNull(threeDimensionalArray); - Assert.True(threeDimensionalArray.GetType().IsArray); - Assert.Equal(3, threeDimensionalArray.GetType().GetArrayRank()); - } - - public interface ITypeWithVector - { - int[] Vector { get; } - } - - public interface ITypeWithTwoDimensionalArray - { - int[,] TwoDimensionalArray { get; } - } - - public interface ITypeWithThreeDimensionalArray - { - int[,,] ThreeDimensionalArray { get; } - } - } - - #endregion 311 - - // Old @ Google Code - - #region #47 - - [Fact] - public void ShouldReturnListFromDateTimeArg() - { - var items = new List() { "Foo", "Bar" }; - - var mock = new Mock(MockBehavior.Strict); - mock - .Setup(m => m.GetValuesSince(It.IsAny())) - .Returns(items); - - var actual = mock.Object.GetValuesSince(DateTime.Now).ToList(); - - Assert.Equal(items.Count, actual.Count); - } + #region 311 + + public sealed class Issue311 + { + [Fact] + public void Can_still_provide_default_value_for_vector() + { + var mocked = Mock.Of(); + + var vector = mocked.Vector; + Assert.NotNull(vector); + Assert.True(vector.GetType().IsArray); + Assert.Equal(1, vector.GetType().GetArrayRank()); + } + + [Fact] + public void Can_provide_default_value_for_twodimensional_array_property() + { + var mocked = Mock.Of(); + + var twoDimensionalArray = mocked.TwoDimensionalArray; + Assert.NotNull(twoDimensionalArray); + Assert.True(twoDimensionalArray.GetType().IsArray); + Assert.Equal(2, twoDimensionalArray.GetType().GetArrayRank()); + } + + [Fact] + public void Can_provide_default_value_for_threedimensional_arrays() + { + var mocked = Mock.Of(); + + var threeDimensionalArray = mocked.ThreeDimensionalArray; + Assert.NotNull(threeDimensionalArray); + Assert.True(threeDimensionalArray.GetType().IsArray); + Assert.Equal(3, threeDimensionalArray.GetType().GetArrayRank()); + } + + public interface ITypeWithVector + { + int[] Vector { get; } + } + + public interface ITypeWithTwoDimensionalArray + { + int[,] TwoDimensionalArray { get; } + } + + public interface ITypeWithThreeDimensionalArray + { + int[,,] ThreeDimensionalArray { get; } + } + } + + #endregion 311 + + // Old @ Google Code + + #region #47 + + [Fact] + public void ShouldReturnListFromDateTimeArg() + { + var items = new List() { "Foo", "Bar" }; + + var mock = new Mock(MockBehavior.Strict); + mock + .Setup(m => m.GetValuesSince(It.IsAny())) + .Returns(items); + + var actual = mock.Object.GetValuesSince(DateTime.Now).ToList(); + + Assert.Equal(items.Count, actual.Count); + } + + public interface IMyClass + { + IEnumerable GetValuesSince(DateTime since); + } + + #endregion + + #region #48 - public interface IMyClass - { - IEnumerable GetValuesSince(DateTime since); - } - - #endregion + public class Issue48 + { + [Fact] + public void ExpectsOnIndexer() + { + var mock = new Mock(); + mock.Setup(m => m[0]).Returns("a"); + mock.Setup(m => m[1]).Returns("b"); - #region #48 + Assert.Equal("a", mock.Object[0]); + Assert.Equal("b", mock.Object[1]); + Assert.Equal(default(string), mock.Object[2]); + } - public class Issue48 - { - [Fact] - public void ExpectsOnIndexer() - { - var mock = new Mock(); - mock.Setup(m => m[0]).Returns("a"); - mock.Setup(m => m[1]).Returns("b"); + public interface ISomeInterface + { + string this[int index] { get; set; } + } + } - Assert.Equal("a", mock.Object[0]); - Assert.Equal("b", mock.Object[1]); - Assert.Equal(default(string), mock.Object[2]); - } + #endregion - public interface ISomeInterface - { - string this[int index] { get; set; } - } - } - - #endregion - - #region #52 + #region #52 - [Fact] - public void ShouldNotOverridePreviousExpectation() - { - var ids = Enumerable.Range(1, 10); - var mock = new Mock(MockBehavior.Strict); + [Fact] + public void ShouldNotOverridePreviousExpectation() + { + var ids = Enumerable.Range(1, 10); + var mock = new Mock(MockBehavior.Strict); - foreach (var id in ids) - { - mock.Setup(x => x.DoSomething(id)); - } + foreach (var id in ids) + { + mock.Setup(x => x.DoSomething(id)); + } - var component = mock.Object; + var component = mock.Object; - foreach (var id in ids) - { - component.DoSomething(id); - } - } + foreach (var id in ids) + { + component.DoSomething(id); + } + } - public interface IOverwritingMethod - { - void DoSomething(int id); - } + public interface IOverwritingMethod + { + void DoSomething(int id); + } - #endregion + #endregion - #region #62 + #region #62 - public interface ISomething - { - void DoSomething() where U : T; - } + public interface ISomething + { + void DoSomething() where U : T; + } - [Fact] - public void CreatesMockWithGenericsConstraints() - { - var mock = new Mock>(); - } + [Fact] + public void CreatesMockWithGenericsConstraints() + { + var mock = new Mock>(); + } - #endregion + #endregion - #region #60 + #region #60 - public interface IFoo - { - void DoThings(object arg); - } + public interface IFoo + { + void DoThings(object arg); + } - [Fact] - public void TwoExpectations() - { - Mock mocked = new Mock(MockBehavior.Strict); - object arg1 = new object(); - object arg2 = new object(); + [Fact] + public void TwoExpectations() + { + Mock mocked = new Mock(MockBehavior.Strict); + object arg1 = new object(); + object arg2 = new object(); - mocked.Setup(m => m.DoThings(arg1)); - mocked.Setup(m => m.DoThings(arg2)); + mocked.Setup(m => m.DoThings(arg1)); + mocked.Setup(m => m.DoThings(arg2)); - mocked.Object.DoThings(arg1); - mocked.Object.DoThings(arg2); + mocked.Object.DoThings(arg1); + mocked.Object.DoThings(arg2); - mocked.VerifyAll(); - } + mocked.VerifyAll(); + } - #endregion + #endregion - #region #21 + #region #21 - [Fact] - public void MatchesLatestExpectations() - { - var mock = new Mock(); + [Fact] + public void MatchesLatestExpectations() + { + var mock = new Mock(); - mock.Setup(m => m.Method(It.IsAny())).Returns(0); - mock.Setup(m => m.Method(It.IsInRange(0, 20, Range.Inclusive))).Returns(1); + mock.Setup(m => m.Method(It.IsAny())).Returns(0); + mock.Setup(m => m.Method(It.IsInRange(0, 20, Range.Inclusive))).Returns(1); - mock.Setup(m => m.Method(5)).Returns(2); - mock.Setup(m => m.Method(10)).Returns(3); + mock.Setup(m => m.Method(5)).Returns(2); + mock.Setup(m => m.Method(10)).Returns(3); - Assert.Equal(3, mock.Object.Method(10)); - Assert.Equal(2, mock.Object.Method(5)); - Assert.Equal(1, mock.Object.Method(6)); - Assert.Equal(0, mock.Object.Method(25)); - } + Assert.Equal(3, mock.Object.Method(10)); + Assert.Equal(2, mock.Object.Method(5)); + Assert.Equal(1, mock.Object.Method(6)); + Assert.Equal(0, mock.Object.Method(25)); + } - public interface IEvaluateLatest - { - int Method(int value); - } + public interface IEvaluateLatest + { + int Method(int value); + } - #endregion + #endregion - #region #49 + #region #49 - [Fact] - public void UsesCustomMatchersWithGenerics() - { - var mock = new Mock(); + [Fact] + public void UsesCustomMatchersWithGenerics() + { + var mock = new Mock(); - mock.Setup(e => e.Method(IsEqual.To(5))).Returns(1); - mock.Setup(e => e.Method(IsEqual.To(6, "foo"))).Returns(2); + mock.Setup(e => e.Method(IsEqual.To(5))).Returns(1); + mock.Setup(e => e.Method(IsEqual.To(6, "foo"))).Returns(2); - Assert.Equal(1, mock.Object.Method(5)); - Assert.Equal(2, mock.Object.Method(6)); - } + Assert.Equal(1, mock.Object.Method(5)); + Assert.Equal(2, mock.Object.Method(6)); + } - public static class IsEqual - { + public static class IsEqual + { #pragma warning disable 618 - [Matcher] - public static T To(T value) - { - return value; - } + [Matcher] + public static T To(T value) + { + return value; + } #pragma warning restore 618 - public static bool To(T left, T right) - { - return left.Equals(right); - } + public static bool To(T left, T right) + { + return left.Equals(right); + } #pragma warning disable 618 - [Matcher] - public static T To(T value, U value2) - { - return value; - } + [Matcher] + public static T To(T value, U value2) + { + return value; + } #pragma warning restore 618 - public static bool To(T left, T right, U value) - { - return left.Equals(right); - } - } - - #endregion - - #region #68 - - [Fact] - public void GetMockCastedToObjectThrows() - { - var mock = new Mock(); - object m = mock.Object; - - Assert.Throws(() => Mock.Get(m)); - } - - #endregion - - #region #69 - - public interface IFooPtr - { - IntPtr Get(string input); - } - - [Fact] - public void ReturnsIntPtr() - { - Mock mock = new Mock(MockBehavior.Strict); - IntPtr ret = new IntPtr(3); - - mock.Setup(m => m.Get("a")).Returns(ret); - - IntPtr ret3 = mock.Object.Get("a"); - - Assert.Equal(ret, mock.Object.Get("a")); - } - - - #endregion - - #region #85 - - public class Issue85 - { - [Fact] - public void FooTest() - { - // Setup - var fooMock = new Mock(); - fooMock.CallBase = true; - fooMock.Setup(o => o.GetBar()).Returns(new Bar()); - var bar = ((IFoolery)fooMock.Object).DoStuffToBar(); - Assert.NotNull(bar); - } - - public interface IFoolery - { - Bar DoStuffToBar(); - } - - public class Foo : IFoolery - { - public virtual Bar GetBar() - { - return new Bar(); - } - - Bar IFoolery.DoStuffToBar() - { - return DoWeirdStuffToBar(); - } - - protected internal virtual Bar DoWeirdStuffToBar() - { - var bar = GetBar(); - //Would do stuff here. - return bar; - } - } - - public class Bar - { - } - } - - #endregion - - #region #89 - - public class Issue89 - { - [Fact] - public void That_last_expectation_should_win() - { - var mock = new Mock(); - mock.Setup(s => s.Get(1)).Returns("blah"); - mock.Setup(s => s.Get(It.IsAny())).Returns("foo"); - mock.Setup(s => s.Get(1)).Returns("bar"); - Assert.Equal("bar", mock.Object.Get(1)); - } - - public interface ISample - { - string Get(int i); - } - } - - #endregion - - #region #128 - - public class Issue128 - { - [Fact] - public void That_CallBase_on_interface_should_not_throw_exception() - { - var mock = new Mock() - { - DefaultValue = DefaultValue.Mock, - CallBase = true - }; - - var service = mock.Object.GetDataService(); - - var data = service.GetData(); - var result = data.Sum(); - - Assert.Equal( 0, result ); - } - - public interface IDataServiceFactory - { - IDataService GetDataService(); - } - - public interface IDataService - { - IList GetData(); - } - } - - #endregion - - #region #134 - - public class Issue134 - { - [Fact] - public void Test() - { - var target = new Mock(); - target.Setup(t => t.Submit(It.IsAny(), It.IsAny(), It.IsAny())); - - var e = Assert.Throws(() => target.VerifyAll()); - - Assert.Contains( - "IFoo t => t.Submit(It.IsAny(), It.IsAny(), new[] { It.IsAny() })", - e.Message); - } - - public interface IFoo - { - void Submit(string mailServer, string from, params int[] toRecipient); - } - } - - #endregion - - #region #136 - - public class _136 - { - // Fixed on PropertiesFixture.cs - } - - #endregion - - #region #138 - - public class _138 - { - public interface SuperFoo - { - string Bar { get; set; } - } - public interface Foo : SuperFoo - { - string Baz { get; set; } - } - - [Fact] - public void superFooMockSetupAllProperties() - { - var repo = new MockRepository(MockBehavior.Default); - var superFooMock = repo.Create(); - superFooMock.SetupAllProperties(); - - var superFoo = superFooMock.Object; - superFoo.Bar = "Bar"; - Assert.Equal("Bar", superFoo.Bar); - } - } - - #endregion + public static bool To(T left, T right, U value) + { + return left.Equals(right); + } + } - #region #145 + #endregion - public class _145 - { - public interface IResolver - { - string Resolve(); - } + #region #68 - public class DataWriter - { - } + [Fact] + public void GetMockCastedToObjectThrows() + { + var mock = new Mock(); + object m = mock.Object; - public class DataA { } - public class DataB { } + Assert.Throws(() => Mock.Get(m)); + } - [Fact] - public void ShouldDifferentiateBetweenGenericsParams() - { - var mock = new Mock(); - mock.Setup(m => m.Resolve>()).Returns("Success A"); + #endregion - Assert.Equal("Success A", mock.Object.Resolve>()); + #region #69 - mock.Setup(m => m.Resolve>()).Returns("Success B"); + public interface IFooPtr + { + IntPtr Get(string input); + } - Assert.Equal("Success B", mock.Object.Resolve>()); - Assert.Equal("Success A", mock.Object.Resolve>()); - } + [Fact] + public void ReturnsIntPtr() + { + Mock mock = new Mock(MockBehavior.Strict); + IntPtr ret = new IntPtr(3); - } + mock.Setup(m => m.Get("a")).Returns(ret); - #endregion + IntPtr ret3 = mock.Object.Get("a"); - #region #111 & #155 + Assert.Equal(ret, mock.Object.Get("a")); + } - public class _111 - { - [Fact] - public void TestTypedParamsWithNoParams() - { - var mock = new Mock(MockBehavior.Strict); - mock.Setup(p => p.Submit(It.IsAny(), It.IsAny())); - mock.Object.Submit("foo"); + #endregion - mock.VerifyAll(); - } + #region #85 - [Fact] - public void TestTypedParams() - { - var mock = new Mock(MockBehavior.Strict); - mock.Setup(p => p.Submit(It.IsAny(), It.IsAny())); + public class Issue85 + { + [Fact] + public void FooTest() + { + // Setup + var fooMock = new Mock(); + fooMock.CallBase = true; + fooMock.Setup(o => o.GetBar()).Returns(new Bar()); + var bar = ((IFoolery)fooMock.Object).DoStuffToBar(); + Assert.NotNull(bar); + } - mock.Object.Submit("foo", 0, 1, 2); - - mock.VerifyAll(); - } - - [Fact] - public void TestObjectParamsWithoutParams() - { - var mock = new Mock(MockBehavior.Strict); - mock.Setup(p => p.Execute(It.IsAny(), It.IsAny())); - - mock.Object.Execute(1); - - mock.VerifyAll(); - } - - [Fact] - public void TestObjectParams() - { - var mock = new Mock(MockBehavior.Strict); - mock.Setup(p => p.Execute(It.IsAny(), It.IsAny())); - - mock.Object.Execute(1, "0", "1", "2"); - - mock.VerifyAll(); - } - - [Fact] - public void TestObjectParamsWithExpectedValues() - { - var mock = new Mock(MockBehavior.Strict); - mock.Setup(p => p.Execute(5, "foo", "bar")); - - Assert.Throws(() => mock.Object.Execute(5, "bar", "foo")); - - mock.Object.Execute(5, "foo", "bar"); - - mock.Verify(p => p.Execute(5, "foo", "bar")); - } - - [Fact] - public void TestObjectParamsWithArray() - { - var mock = new Mock(); - mock.Setup(p => p.Execute(It.IsAny(), It.IsAny(), It.IsAny())); - - mock.Object.Execute(1, new string[] { "0", "1" }, 3); - - mock.Verify(p => p.Execute(It.IsAny(), It.IsAny())); - mock.Verify(p => p.Execute(It.IsAny(), It.IsAny(), It.IsAny())); - mock.Verify(p => p.Execute(It.IsAny(), It.IsAny(), It.IsAny())); - } - - [Fact] - public void TestTypedParamsInEachArgument() - { - var mock = new Mock(MockBehavior.Strict); - mock.Setup(p => p.Submit(It.IsAny(), It.IsAny(), It.IsAny())); - - mock.Object.Submit("foo", 0, 1); - - mock.Verify(p => p.Submit(It.IsAny(), It.IsAny(), It.IsAny())); - mock.Verify(p => p.Submit(It.IsAny(), It.Is(a => a.Length == 2))); - mock.VerifyAll(); - } - - [Fact] - public void TestParamsWithReturnValue() - { - var mock = new Mock(); - mock.Setup(x => x.GetValue("Matt")).Returns("SomeString"); - - var ret = mock.Object.GetValue("Matt"); - Assert.Equal("SomeString", ret); - } - - public interface IParams - { - void Submit(string name, params int[] values); - void Execute(int value, params object[] values); - string GetValue(string name, params object[] args); - } - } - - #endregion - - #region #159 - - public class _159 - { - [Fact] - public void ImplicitIntToLong() - { - int id = 1; - var mock = new Mock(); - mock.Object.SetIt(id); - mock.Verify(x => x.SetIt(id)); - } - - [Fact] - public void ImplicitInterface() - { - var barMock = new Mock(); - var baz = new Baz(barMock.Object); - baz.DoBarFoo(new Foo()); - barMock.Verify(x => x.DoFoo(It.IsAny())); - } - - public interface IFoo - { - long Id { get; set; } - void SetIt(long it); - } - - public class Foo : IFoo - { - public long Id { get; set; } - public void SetIt(long it) { } - } - - public interface IBar - { - void DoFoo(IFoo foo); - } - - public class Baz - { - private readonly IBar _bar; - public Baz(IBar bar) - { - _bar = bar; - } - - public void DoBarFoo(IFoo foo) - { - _bar.DoFoo(foo); - } - } - } - - #endregion - - #region #152 - - public class _152 - { - public enum MembershipCreateStatus { Created, Duplicated, Invalid } - public interface IMembershipService - { - int MinPasswordLength { get; } - bool ValidateUser(string userName, string password); - MembershipCreateStatus CreateUser(string userName, string password, string email); - bool ChangePassword(string userName, string oldPassword, string newPassword); - } - - [Fact] - public void ShouldReturnEnum() - { - var provider = new Mock(); - - // For some reason, this particular lambda doesn't let me specify - // a method return value for the method even though it returns a - // MembershipCreateStatus enum - provider.Setup(p => p.CreateUser(string.Empty, string.Empty, string.Empty)).Returns(MembershipCreateStatus.Invalid); - - Assert.Equal(MembershipCreateStatus.Invalid, provider.Object.CreateUser("", "", "")); - } - } - - #endregion - - #region #153 - - public class _153 - { - public struct SomeClass // Struct just to avoid having to implement Equals/GetHashCode - { - public static implicit operator SomeClass(T t) - { - return new SomeClass(); - } - - public static SomeClass From(T t) - { - return t; - } - } - - public interface IIfc - { - int Get(SomeClass id); - } - - public class ImplicitConversionProblem - { - [Fact] - public void ImplicitSetupVerifyAll_Fails() - { - const string s = "XYZ"; - var mock = new Mock(); - mock.Setup(ifc => ifc.Get(s)).Returns(17); - - var result = mock.Object.Get(s); - - mock.VerifyAll(); // MockVerificationException here - Assert.Equal(17, result); - } - - [Fact] - public void ExplicitSetupVerifyAll_Works() - { - const string s = "XYZ"; - var mock = new Mock(); - mock.Setup(ifc => ifc.Get(SomeClass.From(s))).Returns(17); - - var result = mock.Object.Get(s); - - mock.VerifyAll(); - Assert.Equal(17, result); - } - - [Fact] - public void ExplicitSetupImplicitVerification_Fails() - { - const string s = "XYZ"; - var mock = new Mock(); - mock.Setup(ifc => ifc.Get(SomeClass.From(s))).Returns(17); - - var result = mock.Object.Get(s); - - // Here the problem can be seen even in the exception message: - // Invocation was not performed on the mock: ifc => ifc.Get("XYZ") - // -----------------------------------------------------------^ - mock.Verify(ifc => ifc.Get(s)); - Assert.Equal(17, result); - } - - [Fact] - public void ImplicitSetupExplicitVerification_Fails() - { - const string s = "XYZ"; - var mock = new Mock(); - mock.Setup(ifc => ifc.Get(s)).Returns(17); - - var result = mock.Object.Get(s); - - // This verification passes oddly enough - mock.Verify(ifc => ifc.Get(SomeClass.From(s))); - - // This assert fails, indicating that the setup was not used - Assert.Equal(17, result); - } - } - } - - #endregion - - #region #146 - - public class _146 - { - public interface IFoo - { - bool Property { get; set; } - string StringProperty { get; set; } - } - - [Fact] - public void StrictMockPropertySet() - { - var mock = new Mock(MockBehavior.Strict); - - mock.SetupSet(v => v.Property = false); - - Assert.Throws(() => mock.VerifySet(v => v.Property = false)); - - mock.Object.Property = false; - - mock.VerifySet(v => v.Property = false); - } - } - - #endregion - - #region #158 - - public class _158 - { - public class Foo - { - public virtual void Boo() - { - Bar(); - Bar(); - } - - protected virtual void Bar() - { - } - } + public interface IFoolery + { + Bar DoStuffToBar(); + } -#pragma warning disable 618 - [Fact(Skip = "This setup doesn't make sense, and xUnit does not provide this message checking capability.")] - public void ShouldRenderCustomMessage() - { - var foo = new Mock { CallBase = true }; - foo.Protected().Setup("Bar").AtMostOnce().Verifiable("Hello"); - foo.Object.Boo(); - //Assert.Throws("Hello", () => foo.Object.Boo()); - } -#pragma warning restore 618 - } + public class Foo : IFoolery + { + public virtual Bar GetBar() + { + return new Bar(); + } - #endregion + Bar IFoolery.DoStuffToBar() + { + return DoWeirdStuffToBar(); + } - #region #160 + protected internal virtual Bar DoWeirdStuffToBar() + { + var bar = GetBar(); + //Would do stuff here. + return bar; + } + } -#if !NETCORE - public class _160 - { - [Fact] - public void ShouldMockHtmlControl() - { - // CallBase was missing - var htmlInputTextMock = new Mock() { CallBase = true }; - Assert.True(htmlInputTextMock.Object.Visible); - } - } -#endif + public class Bar + { + } + } - #endregion + #endregion - #region #161 + #region #89 - public class _161 - { - [Fact] - public void InvertEqualObjects() - { - var foo1 = new Foo { Id = "1" }; - var foo = new Foo { Id = "2" }; + public class Issue89 + { + [Fact] + public void That_last_expectation_should_win() + { + var mock = new Mock(); + mock.Setup(s => s.Get(1)).Returns("blah"); + mock.Setup(s => s.Get(It.IsAny())).Returns("foo"); + mock.Setup(s => s.Get(1)).Returns("bar"); + Assert.Equal("bar", mock.Object.Get(1)); + } - var dependency = new Mock(); + public interface ISample + { + string Get(int i); + } + } - dependency.Setup(x => x.DoThis(foo, foo1)) - .Returns(new Foo()); - - var f = dependency.Object.DoThis(foo, foo1); - - dependency.Verify(x => x.DoThis(foo, foo1)); - dependency.Verify(x => x.DoThis(foo1, foo), Times.Never()); - } + #endregion - [Fact(Skip = "Wrong Equals implemention in the report. Won't Fix")] - public void ExampleFailingTest() - { - var foo1 = new Foo(); - var foo = new Foo(); - - var sut = new Perfectly_fine_yet_failing_test(); - var dependency = new Mock(); - - dependency.Setup(x => x.DoThis(foo, foo1)) - .Returns(new Foo()); - - sut.Do(dependency.Object, foo, foo1); + #region #128 - dependency.Verify(x => x.DoThis(foo, foo1)); - dependency.Verify(x => x.DoThis(foo1, foo), Times.Never()); - } + public class Issue128 + { + [Fact] + public void That_CallBase_on_interface_should_not_throw_exception() + { + var mock = new Mock() + { + DefaultValue = DefaultValue.Mock, + CallBase = true + }; - public class Perfectly_fine_yet_failing_test - { - public void Do(IDependency dependency, Foo foo, Foo foo1) - { - var foo2 = dependency.DoThis(foo, foo1); - if (foo2 == null) - foo2 = dependency.DoThis(foo1, foo); - } - } - - public interface IDependency - { - Foo DoThis(Foo foo, Foo foo1); - } + var service = mock.Object.GetDataService(); - public class Foo - { - public string Id { get; set; } + var data = service.GetData(); + var result = data.Sum(); - public override bool Equals(object obj) - { - return obj is Foo && ((Foo)obj).Id == Id; - } - - public override int GetHashCode() - { - return base.GetHashCode(); - } - } - } + Assert.Equal( 0, result ); + } - #endregion + public interface IDataServiceFactory + { + IDataService GetDataService(); + } - #region #174 - - public class _174 - { - [Fact] - public void Test() - { - var serviceNo1Mock = new Mock(); - var collaboratorMock = new Mock(); - - collaboratorMock.Object.Collaborate(serviceNo1Mock.Object); + public interface IDataService + { + IList GetData(); + } + } - collaboratorMock.Verify(o => o.Collaborate(serviceNo1Mock.Object)); - } - - public interface ISomeCollaborator - { - void Collaborate(IServiceNo1 serviceNo1); - } - - public interface IServiceNo1 : IEnumerable - { - } - } - - #endregion - - #region #177 - - public class _177 - { - [Fact] - public void Test() - { - var mock = new Mock(); - Assert.NotNull(mock.Object); - } - - public interface IMyInterface - { - void DoStuff() where TTo : TFrom; - } - } - - #endregion - - #region #184 - - public class _184 - { - [Fact] - public void Test() - { - var fooRaised = false; - var barRaised = false; - - var fooMock = new Mock(); - var barMock = fooMock.As(); - - fooMock.Object.FooEvent += (s, e) => fooRaised = true; - barMock.Object.BarEvent += (s, e) => barRaised = true; - - fooMock.Raise(m => m.FooEvent += null, EventArgs.Empty); - barMock.Raise(m => m.BarEvent += null, EventArgs.Empty); - - Assert.True(fooRaised); - Assert.True(barRaised); - } - - public interface IFoo - { - event EventHandler FooEvent; - } - - public interface IBar - { - event EventHandler BarEvent; - } - } - - #endregion - - #region #185 - - public class _185 - { - [Fact] - public void Test() - { - var mock = new Mock>(); - Assert.Throws(() => mock.Setup(l => l.FirstOrDefault()).Returns("Hello world")); - } - } - - #endregion - - #region #187 - - public class _187 - { - [Fact] - public void Test() - { - var mock = new Mock(); - - mock.Setup(r => r.Get()).Returns(new Object()); - mock.Setup(r => r.Get()).Returns(new Object()); - - Assert.NotNull(mock.Object.Get()); - Assert.NotNull(mock.Object.Get()); - } - - public class Foo - { - public class Inner - { - } - } - - public class Bar - { - public class Inner - { - } - } - - public interface IGeneric - { - object Get() where T : new(); - } - } - - #endregion - - #region #183 - - public class _183 - { - [Fact] - public void Test() - { - var mock = new Mock(); - mock.Setup(m => m.Execute(1)); - mock.Setup(m => m.Execute(It.IsInRange(2, 20, Range.Exclusive))); - mock.Setup(m => m.Execute(3, "Caption")); - - mock.Object.Execute(3); - mock.Object.Execute(4); - mock.Object.Execute(5); - - var e = Assert.Throws(() => mock.Verify(m => m.Execute(0))); - Assert.Contains( - "\r\nConfigured setups:" + - "\r\nm => m.Execute(1), Times.Never" + - "\r\nm => m.Execute(It.IsInRange(2, 20, Range.Exclusive)), Times.Exactly(3)", - e.Message); - } - - [Fact] - public void TestGeneric() - { - var mock = new Mock(); - mock.Setup(m => m.Execute(1, 10)); - mock.Setup(m => m.Execute(1, "Foo")); - - mock.Object.Execute(1, 10); - - var e = Assert.Throws(() => mock.Verify(m => m.Execute(1, 1))); - Assert.Contains( - "\r\nConfigured setups:\r\nm => m.Execute(1, 10), Times.Once", - e.Message); - } - - [Fact] - public void TestNoSetups() - { - var mock = new Mock(); - - var e = Assert.Throws(() => mock.Verify(m => m.Execute(1))); - Assert.Contains("\r\nNo setups configured.", e.Message); - - } - - public interface IFoo - { - void Execute(int param); - void Execute(int param, string caption); - void Execute(int p, T param); - } - } - - #endregion - - #region #186 - - public class _186 - { - [Fact] - public void TestVerifyMessage() - { - var mock = new Mock(); - mock.Setup(m => m.OnExecute()); - - var e = Assert.Throws(() => mock.Verify(m => m.Execute())); - Assert.True(e.Message.StartsWith("Invalid verify")); - } - - public class Foo - { - public void Execute() - { - this.OnExecute(); - } - - public virtual void OnExecute() - { - throw new NotImplementedException(); - } - } - } - - #endregion - - #region #190 - - public class _190 - { - [Fact] - public void Test() - { - var mock = new Mock().As(); - mock.SetupAllProperties(); - - ISite site = new FooSite(); - mock.Object.Site = site; - Assert.Same(site, mock.Object.Site); - } - - public class FooSite : ISite - { - public IComponent Component - { - get { throw new NotImplementedException(); } - } - - public IContainer Container - { - get { throw new NotImplementedException(); } - } - - public bool DesignMode - { - get { throw new NotImplementedException(); } - } - - public string Name - { - get { throw new NotImplementedException(); } - set { throw new NotImplementedException(); } - } - - public object GetService(Type serviceType) - { - throw new NotImplementedException(); - } - } - - } - - #endregion - - #region #204 - - public class _204 - { - [Fact] - public void Test() - { - var mock = new Mock(); - mock.Setup(x => x.Select(u => u.Id == 100)) - .Returns(new User() { Id = 100 }); - - var user = mock.Object.Select(usr => usr.Id == 100); - Assert.Equal(100, user.Id); - mock.Verify(x => x.Select(usr => usr.Id == 100), Times.Once()); - - user = mock.Object.Select(usr => usr.Id == 101); - Assert.Null(user); - mock.Verify(x => x.Select(usr => usr.Id == 101), Times.Once()); - - mock.Verify(x => x.Select(usr => usr.Id == 102), Times.Never()); - mock.Verify(x => x.Select(It.IsAny>>()), Times.Exactly(2)); - } - - public interface IRepository - { - T Select(Expression> filter) where T : class; - } - - public class User - { - public int Id { get; set; } - } - } - - #endregion - - #region #205 - - public class _205 - { - [Fact] - public void Test() - { - new Mock().SetupAllProperties(); - } - - public interface IFoo - { - string Error { get; set; } - string this[int index] { get; set; } - } - } - - #endregion - - #region #223 - - public class _223 - { - [Fact] - public void TestSetup() - { - this.TestSetupHelper(); - } - - public void TestSetupHelper() where T : class, IFoo - { - var expected = 2; - - var target = new Mock(); - target.Setup(p => p.DoInt32(0)).Returns(expected); - target.Setup(p => p.DoGeneric(0)).Returns(expected); - - Assert.Equal(expected, target.Object.DoInt32(0)); - Assert.Equal(expected, target.Object.DoGeneric(0)); - } - - public interface IFoo - { - int DoInt32(int value); - T DoGeneric(int value); - } - - public class Foo : IFoo - { - public virtual int DoInt32(int value) - { - return 4; - } - - public virtual int DoGeneric(int value) - { - return 5; - } - } - } - - #endregion + #endregion - #region #228 + #region #134 - public class _228 + public class Issue134 { [Fact] public void Test() { - var mock = new Mock() { CallBase = true }; - IFoo foo = mock.Object; - IBar bar = mock.Object; + var target = new Mock(); + target.Setup(t => t.Submit(It.IsAny(), It.IsAny(), It.IsAny())); - bool fooRaised = false; - bool barRaised = false; - foo.Foo += (s, e) => fooRaised = true; - bar.Bar += (s, e) => barRaised = true; + var e = Assert.Throws(() => target.VerifyAll()); - mock.Object.RaiseMyEvents(); - - Assert.True(fooRaised); - Assert.True(barRaised); + Assert.Contains( + "IFoo t => t.Submit(It.IsAny(), It.IsAny(), new[] { It.IsAny() })", + e.Message); } public interface IFoo { - event EventHandler Foo; + void Submit(string mailServer, string from, params int[] toRecipient); } + } - public interface IBar + #endregion + + #region #136 + + public class _136 + { + // Fixed on PropertiesFixture.cs + } + + #endregion + + #region #138 + + public class _138 + { + public interface SuperFoo { - event EventHandler Bar; + string Bar { get; set; } + } + public interface Foo : SuperFoo + { + string Baz { get; set; } } - public class FooBar : IFoo, IBar + [Fact] + public void superFooMockSetupAllProperties() { - public event EventHandler Foo; - public event EventHandler Bar; + var repo = new MockRepository(MockBehavior.Default); + var superFooMock = repo.Create(); + superFooMock.SetupAllProperties(); - public void RaiseMyEvents() - { - if (this.Foo != null) - { - this.Foo(this, EventArgs.Empty); - } - if (this.Bar != null) - { - this.Bar(this, EventArgs.Empty); - } - } + var superFoo = superFooMock.Object; + superFoo.Bar = "Bar"; + Assert.Equal("Bar", superFoo.Bar); } } #endregion - #region #229 + #region #145 + + public class _145 + { + public interface IResolver + { + string Resolve(); + } + + public class DataWriter + { + } + + public class DataA { } + public class DataB { } - public class _229 - { - [Fact] - public void Test() - { - var target = new Mock { CallBase = true }; - - var raised = false; - target.Object.MyEvent += (s, e) => raised = true; - target.Object.RaiseMyEvent(); - - Assert.True(raised); - } - - public class Foo - { - public virtual event EventHandler MyEvent; - - public void RaiseMyEvent() - { - if (this.MyEvent != null) - { - this.MyEvent(this, EventArgs.Empty); - } - } - } - } - - #endregion - - #region #230 - - public class _230 - { - [Fact] - public void ByteArrayCallbackArgumentShouldNotBeNull() - { - var data = new byte[] { 2, 1, 2 }; - var stream = new Mock(); - - stream.SetupGet(m => m.Length) - .Returns(data.Length); - stream.Setup(m => m.Read(It.IsAny(), It.IsAny(), It.IsAny())) - .Callback((b, o, c) => data.CopyTo(b, 0)) - .Returns(data.Length); - - var contents = new byte[stream.Object.Length]; - stream.Object.Read(contents, 0, (int)stream.Object.Length); - } - } - - #endregion - - #region #232 - - public class _232 - { - [Fact] - public void Test() - { - var repository = new Mock(); - var svc = new Service(repository.Object); - - svc.Create(); - - repository.Verify(r => r.Insert(It.IsAny()), Times.Once()); - repository.Verify(r => r.Insert(It.IsAny()), Times.Once()); - repository.Verify(r => r.Insert(It.IsAny()), Times.Exactly(2)); - } - - public interface IRepository - { - void Insert(IEntity entity); - } - - public interface IEntity - { - } - - public class Foo : IEntity - { - } - - public class Bar : IEntity - { - } - - public class Service - { - private IRepository repository; - - public Service(IRepository repository) - { - this.repository = repository; - } - - public void Create() - { - repository.Insert(new Foo()); - repository.Insert(new Bar()); - } - } - } - - #endregion - - #region #242 - - public class _242 - { - [Fact] - public void PropertyChangedTest() - { - var mock = new Mock(); - int callbacks = 0; - mock.Object.PropertyChanged += (sender, args) => callbacks++; - - mock.Raise(m => m.PropertyChanged += null, new PropertyChangedEventArgs("Foo")); - Assert.Equal(1, callbacks); - } - - public class PropertyChangedBase : INotifyPropertyChanged - { - public virtual event PropertyChangedEventHandler PropertyChanged = (s, e) => { }; - } - - public class PropertyChangedInherited : PropertyChangedBase - { - } - } - - #endregion - - #region #245 - - public class _245 - { - [Fact] - public void Test() - { - var mock = new Mock(); - - ITest instance; - instance = mock.Object; - } - - public interface ITest - { - void Do() where T2 : T1; - } - } - - #endregion - - #region #251 - - public class _251 - { - [Fact] - public void Test() - { - var repositoryMock = new Mock>(); - - var repository = repositoryMock.Object; - repository.Save("test"); - - repositoryMock.Verify(m => m.Save("test")); - } - - public interface IRepository - { - void Save(string value); - } - - public interface IRepository : IRepository - { - void Save(T value); - } - } - - #endregion - - #region #256 - - public class _256 - { - [Fact] - public void TestFinalizeNotMocked() - { - var mock = new Mock(MockBehavior.Strict); - mock.Setup(m => m.Foo).Returns(10); - mock.Setup(m => m.Bar).Returns("Hello mocked world!"); - var instance = mock.Object; - - Assert.Equal(10, instance.Foo); - } - - public class ClassWithFinalizer - { - public virtual int Foo { get; set; } - public virtual string Bar { get; set; } - - ~ClassWithFinalizer() - { - - } - } - } - - #endregion - - #region #261 - - public class _261 - { - [Fact] - public void Test() - { - var mock = new Mock(); - mock.Protected().SetupSet("Status", 42); - - mock.Object.SetStatus(42); - - mock.Protected().VerifySet("Status", Times.Once(), 42); - } - - public class Foo - { - public virtual int Status { get; protected set; } - - internal void SetStatus(int value) - { - this.Status = value; - } - } - } - - #endregion - - #region #267 - - public class _267 - { - public interface IPerformOperation - { - string Operation(object input); - } - - public class OperationUser - { - private readonly IPerformOperation m_OperationPerformer; - - public OperationUser(IPerformOperation operationPerformer) - { - m_OperationPerformer = operationPerformer; - } - - public string DoOperation(object input) - { - return m_OperationPerformer.Operation(input); - } - } - - public class HelperSetup - { - private Mock m_OperationStub; - - public HelperSetup() - { - m_OperationStub = new Mock(); - } - - [Fact] - public void InlineSetupTest() - { - m_OperationStub.Setup(m => m.Operation(It.IsAny())).Returns(value => "test"); - m_OperationStub.Setup(m => m.Operation(It.IsAny())).Returns(value => "25"); - - var operationUser = new OperationUser(m_OperationStub.Object); - - var intOperationResult = operationUser.DoOperation(9); - var stringOperationResult = operationUser.DoOperation("Hello"); - - Assert.Equal("25", intOperationResult); - Assert.Equal("test", stringOperationResult); - } - - [Fact] - public void HelperSetupTest() - { - SetupOperationStub(value => "test"); - SetupOperationStub(value => "25"); + [Fact] + public void ShouldDifferentiateBetweenGenericsParams() + { + var mock = new Mock(); + mock.Setup(m => m.Resolve>()).Returns("Success A"); + + Assert.Equal("Success A", mock.Object.Resolve>()); + + mock.Setup(m => m.Resolve>()).Returns("Success B"); + + Assert.Equal("Success B", mock.Object.Resolve>()); + Assert.Equal("Success A", mock.Object.Resolve>()); + } + + } - var operationUser = new OperationUser(m_OperationStub.Object); + #endregion - var intOperationResult = operationUser.DoOperation(9); - var stringOperationResult = operationUser.DoOperation("Hello"); - - Assert.Equal("25", intOperationResult); - Assert.Equal("test", stringOperationResult); - } + #region #111 & #155 - private void SetupOperationStub(Func valueFunction) - { - m_OperationStub.Setup(m => m.Operation(It.IsAny())).Returns(valueFunction); - } - } - } + public class _111 + { + [Fact] + public void TestTypedParamsWithNoParams() + { + var mock = new Mock(MockBehavior.Strict); + mock.Setup(p => p.Submit(It.IsAny(), It.IsAny())); - #endregion + mock.Object.Submit("foo"); - #region #273 - - public class _273 - { - [Fact] - public void WhenMockingAnExternalInterface_ThenItWorks() - { - Assert.NotNull(new Mock().Object); - Assert.NotNull(Mock.Of()); - Assert.NotNull(new Mock().Object); - Assert.NotNull(new Mock().Object); - Assert.NotNull(Mock.Of()); - Assert.NotNull(new Mock().Object); - Assert.NotNull(new Mock().Object); - } - - public class Baz : ClassLibrary2.Bar - { - } - } - - #endregion - - #region #325 + mock.VerifyAll(); + } - public class _325 - { - [Fact] - public void SubscribingWorks() - { - var target = new Mock { CallBase = true }; - target.As(); - - var bar = (IBar)target.Object; - var raised = false; - bar.SomeEvent += (sender, e) => raised = true; + [Fact] + public void TestTypedParams() + { + var mock = new Mock(MockBehavior.Strict); + mock.Setup(p => p.Submit(It.IsAny(), It.IsAny())); - target.As().Raise(b => b.SomeEvent += null, EventArgs.Empty); - - Assert.True(raised); - } - - [Fact] - public void UnsubscribingWorks() - { - var target = new Mock { CallBase = true }; - target.As(); + mock.Object.Submit("foo", 0, 1, 2); - var bar = (IBar)target.Object; - var raised = false; - EventHandler handler = (sender, e) => raised = true; - bar.SomeEvent += handler; - bar.SomeEvent -= handler; + mock.VerifyAll(); + } - target.As().Raise(b => b.SomeEvent += null, EventArgs.Empty); + [Fact] + public void TestObjectParamsWithoutParams() + { + var mock = new Mock(MockBehavior.Strict); + mock.Setup(p => p.Execute(It.IsAny(), It.IsAny())); - Assert.False(raised); - } + mock.Object.Execute(1); - public class Foo - { - } + mock.VerifyAll(); + } - public interface IBar - { - event EventHandler SomeEvent; - } + [Fact] + public void TestObjectParams() + { + var mock = new Mock(MockBehavior.Strict); + mock.Setup(p => p.Execute(It.IsAny(), It.IsAny())); - } + mock.Object.Execute(1, "0", "1", "2"); - #endregion + mock.VerifyAll(); + } - #region #326 + [Fact] + public void TestObjectParamsWithExpectedValues() + { + var mock = new Mock(MockBehavior.Strict); + mock.Setup(p => p.Execute(5, "foo", "bar")); -#if !NETCORE + Assert.Throws(() => mock.Object.Execute(5, "bar", "foo")); - public class _326 - { - [Fact] - public void ShouldSupportMockingWinFormsControl() - { - var foo = new Mock(); - var bar = foo.Object; - } - } + mock.Object.Execute(5, "foo", "bar"); -#endif + mock.Verify(p => p.Execute(5, "foo", "bar")); + } - #endregion - - #region Recursive issue - - public class RecursiveFixture - { - [Fact] - public void TestRecursive() - { - var mock = new Mock() { DefaultValue = DefaultValue.Mock }; - mock.Setup(c => c.HttpContext.Response.Write("stuff")); - - mock.Object.HttpContext.Response.Write("stuff"); - mock.Object.HttpContext.Response.ShouldEncode = true; - - Assert.Throws(() => mock.VerifySet( - c => c.HttpContext.Response.ShouldEncode = It.IsAny(), - Times.Never())); - } - - public class ControllerContext - { - public virtual HttpContext HttpContext { get; set; } - } - - public abstract class HttpContext - { - protected HttpContext() - { - } - - public virtual HttpResponse Response - { - get { throw new NotImplementedException(); } - } - } - - public abstract class HttpResponse - { - protected HttpResponse() - { - } - - public virtual bool ShouldEncode - { - get { throw new NotImplementedException(); } - set { throw new NotImplementedException(); } - } - - public virtual void Write(string s) - { - throw new NotImplementedException(); - } - } - } - - #endregion - - #region #250 - - public class _250 - { - [Fact] - public void Test() - { - var target = new Mock(); - - Assert.NotNull(target.Object); - } - } - - #endregion - - #region Matcher should work with Convert - - public class MatcherConvertFixture - { - public interface IFoo - { - string M(long l); - } - - [Fact] - public void MatcherDoesNotIgnoreConvert() - { - var mock = new Mock(MockBehavior.Strict); - mock.Setup(x => x.M(int.Parse("2"))).Returns("OK"); - Assert.Equal("OK", mock.Object.M(2L)); - } - } - - #endregion - } + [Fact] + public void TestObjectParamsWithArray() + { + var mock = new Mock(); + mock.Setup(p => p.Execute(It.IsAny(), It.IsAny(), It.IsAny())); + + mock.Object.Execute(1, new string[] { "0", "1" }, 3); + + mock.Verify(p => p.Execute(It.IsAny(), It.IsAny())); + mock.Verify(p => p.Execute(It.IsAny(), It.IsAny(), It.IsAny())); + mock.Verify(p => p.Execute(It.IsAny(), It.IsAny(), It.IsAny())); + } + + [Fact] + public void TestTypedParamsInEachArgument() + { + var mock = new Mock(MockBehavior.Strict); + mock.Setup(p => p.Submit(It.IsAny(), It.IsAny(), It.IsAny())); + + mock.Object.Submit("foo", 0, 1); + + mock.Verify(p => p.Submit(It.IsAny(), It.IsAny(), It.IsAny())); + mock.Verify(p => p.Submit(It.IsAny(), It.Is(a => a.Length == 2))); + mock.VerifyAll(); + } + + [Fact] + public void TestParamsWithReturnValue() + { + var mock = new Mock(); + mock.Setup(x => x.GetValue("Matt")).Returns("SomeString"); + + var ret = mock.Object.GetValue("Matt"); + Assert.Equal("SomeString", ret); + } + + public interface IParams + { + void Submit(string name, params int[] values); + void Execute(int value, params object[] values); + string GetValue(string name, params object[] args); + } + } + + #endregion + + #region #159 + + public class _159 + { + [Fact] + public void ImplicitIntToLong() + { + int id = 1; + var mock = new Mock(); + mock.Object.SetIt(id); + mock.Verify(x => x.SetIt(id)); + } + + [Fact] + public void ImplicitInterface() + { + var barMock = new Mock(); + var baz = new Baz(barMock.Object); + baz.DoBarFoo(new Foo()); + barMock.Verify(x => x.DoFoo(It.IsAny())); + } + + public interface IFoo + { + long Id { get; set; } + void SetIt(long it); + } + + public class Foo : IFoo + { + public long Id { get; set; } + public void SetIt(long it) { } + } + + public interface IBar + { + void DoFoo(IFoo foo); + } + + public class Baz + { + private readonly IBar _bar; + public Baz(IBar bar) + { + _bar = bar; + } + + public void DoBarFoo(IFoo foo) + { + _bar.DoFoo(foo); + } + } + } + + #endregion + + #region #152 + + public class _152 + { + public enum MembershipCreateStatus { Created, Duplicated, Invalid } + public interface IMembershipService + { + int MinPasswordLength { get; } + bool ValidateUser(string userName, string password); + MembershipCreateStatus CreateUser(string userName, string password, string email); + bool ChangePassword(string userName, string oldPassword, string newPassword); + } + + [Fact] + public void ShouldReturnEnum() + { + var provider = new Mock(); + + // For some reason, this particular lambda doesn't let me specify + // a method return value for the method even though it returns a + // MembershipCreateStatus enum + provider.Setup(p => p.CreateUser(string.Empty, string.Empty, string.Empty)).Returns(MembershipCreateStatus.Invalid); + + Assert.Equal(MembershipCreateStatus.Invalid, provider.Object.CreateUser("", "", "")); + } + } + + #endregion + + #region #153 + + public class _153 + { + public struct SomeClass // Struct just to avoid having to implement Equals/GetHashCode + { + public static implicit operator SomeClass(T t) + { + return new SomeClass(); + } + + public static SomeClass From(T t) + { + return t; + } + } + + public interface IIfc + { + int Get(SomeClass id); + } + + public class ImplicitConversionProblem + { + [Fact] + public void ImplicitSetupVerifyAll_Fails() + { + const string s = "XYZ"; + var mock = new Mock(); + mock.Setup(ifc => ifc.Get(s)).Returns(17); + + var result = mock.Object.Get(s); + + mock.VerifyAll(); // MockVerificationException here + Assert.Equal(17, result); + } + + [Fact] + public void ExplicitSetupVerifyAll_Works() + { + const string s = "XYZ"; + var mock = new Mock(); + mock.Setup(ifc => ifc.Get(SomeClass.From(s))).Returns(17); + + var result = mock.Object.Get(s); + + mock.VerifyAll(); + Assert.Equal(17, result); + } + + [Fact] + public void ExplicitSetupImplicitVerification_Fails() + { + const string s = "XYZ"; + var mock = new Mock(); + mock.Setup(ifc => ifc.Get(SomeClass.From(s))).Returns(17); + + var result = mock.Object.Get(s); + + // Here the problem can be seen even in the exception message: + // Invocation was not performed on the mock: ifc => ifc.Get("XYZ") + // -----------------------------------------------------------^ + mock.Verify(ifc => ifc.Get(s)); + Assert.Equal(17, result); + } + + [Fact] + public void ImplicitSetupExplicitVerification_Fails() + { + const string s = "XYZ"; + var mock = new Mock(); + mock.Setup(ifc => ifc.Get(s)).Returns(17); + + var result = mock.Object.Get(s); + + // This verification passes oddly enough + mock.Verify(ifc => ifc.Get(SomeClass.From(s))); + + // This assert fails, indicating that the setup was not used + Assert.Equal(17, result); + } + } + } + + #endregion + + #region #146 + + public class _146 + { + public interface IFoo + { + bool Property { get; set; } + string StringProperty { get; set; } + } + + [Fact] + public void StrictMockPropertySet() + { + var mock = new Mock(MockBehavior.Strict); + + mock.SetupSet(v => v.Property = false); + + Assert.Throws(() => mock.VerifySet(v => v.Property = false)); + + mock.Object.Property = false; + + mock.VerifySet(v => v.Property = false); + } + } + + #endregion + + #region #158 + + public class _158 + { + public class Foo + { + public virtual void Boo() + { + Bar(); + Bar(); + } + + protected virtual void Bar() + { + } + } + +#pragma warning disable 618 + [Fact(Skip = "This setup doesn't make sense, and xUnit does not provide this message checking capability.")] + public void ShouldRenderCustomMessage() + { + var foo = new Mock { CallBase = true }; + foo.Protected().Setup("Bar").AtMostOnce().Verifiable("Hello"); + foo.Object.Boo(); + //Assert.Throws("Hello", () => foo.Object.Boo()); + } +#pragma warning restore 618 + } + + #endregion + + #region #160 + +#if !NETCORE + public class _160 + { + [Fact] + public void ShouldMockHtmlControl() + { + // CallBase was missing + var htmlInputTextMock = new Mock() { CallBase = true }; + Assert.True(htmlInputTextMock.Object.Visible); + } + } +#endif + + #endregion + + #region #161 + + public class _161 + { + [Fact] + public void InvertEqualObjects() + { + var foo1 = new Foo { Id = "1" }; + var foo = new Foo { Id = "2" }; + + var dependency = new Mock(); + + dependency.Setup(x => x.DoThis(foo, foo1)) + .Returns(new Foo()); + + var f = dependency.Object.DoThis(foo, foo1); + + dependency.Verify(x => x.DoThis(foo, foo1)); + dependency.Verify(x => x.DoThis(foo1, foo), Times.Never()); + } + + [Fact(Skip = "Wrong Equals implemention in the report. Won't Fix")] + public void ExampleFailingTest() + { + var foo1 = new Foo(); + var foo = new Foo(); + + var sut = new Perfectly_fine_yet_failing_test(); + var dependency = new Mock(); + + dependency.Setup(x => x.DoThis(foo, foo1)) + .Returns(new Foo()); + + sut.Do(dependency.Object, foo, foo1); + + dependency.Verify(x => x.DoThis(foo, foo1)); + dependency.Verify(x => x.DoThis(foo1, foo), Times.Never()); + } + + public class Perfectly_fine_yet_failing_test + { + public void Do(IDependency dependency, Foo foo, Foo foo1) + { + var foo2 = dependency.DoThis(foo, foo1); + if (foo2 == null) + foo2 = dependency.DoThis(foo1, foo); + } + } + + public interface IDependency + { + Foo DoThis(Foo foo, Foo foo1); + } + + public class Foo + { + public string Id { get; set; } + + public override bool Equals(object obj) + { + return obj is Foo && ((Foo)obj).Id == Id; + } + + public override int GetHashCode() + { + return base.GetHashCode(); + } + } + } + + #endregion + + #region #174 + + public class _174 + { + [Fact] + public void Test() + { + var serviceNo1Mock = new Mock(); + var collaboratorMock = new Mock(); + + collaboratorMock.Object.Collaborate(serviceNo1Mock.Object); + + collaboratorMock.Verify(o => o.Collaborate(serviceNo1Mock.Object)); + } + + public interface ISomeCollaborator + { + void Collaborate(IServiceNo1 serviceNo1); + } + + public interface IServiceNo1 : IEnumerable + { + } + } + + #endregion + + #region #177 + + public class _177 + { + [Fact] + public void Test() + { + var mock = new Mock(); + Assert.NotNull(mock.Object); + } + + public interface IMyInterface + { + void DoStuff() where TTo : TFrom; + } + } + + #endregion + + #region #184 + + public class _184 + { + [Fact] + public void Test() + { + var fooRaised = false; + var barRaised = false; + + var fooMock = new Mock(); + var barMock = fooMock.As(); + + fooMock.Object.FooEvent += (s, e) => fooRaised = true; + barMock.Object.BarEvent += (s, e) => barRaised = true; + + fooMock.Raise(m => m.FooEvent += null, EventArgs.Empty); + barMock.Raise(m => m.BarEvent += null, EventArgs.Empty); + + Assert.True(fooRaised); + Assert.True(barRaised); + } + + public interface IFoo + { + event EventHandler FooEvent; + } + + public interface IBar + { + event EventHandler BarEvent; + } + } + + #endregion + + #region #185 + + public class _185 + { + [Fact] + public void Test() + { + var mock = new Mock>(); + Assert.Throws(() => mock.Setup(l => l.FirstOrDefault()).Returns("Hello world")); + } + } + + #endregion + + #region #187 + + public class _187 + { + [Fact] + public void Test() + { + var mock = new Mock(); + + mock.Setup(r => r.Get()).Returns(new Object()); + mock.Setup(r => r.Get()).Returns(new Object()); + + Assert.NotNull(mock.Object.Get()); + Assert.NotNull(mock.Object.Get()); + } + + public class Foo + { + public class Inner + { + } + } + + public class Bar + { + public class Inner + { + } + } + + public interface IGeneric + { + object Get() where T : new(); + } + } + + #endregion + + #region #183 + + public class _183 + { + [Fact] + public void Test() + { + var mock = new Mock(); + mock.Setup(m => m.Execute(1)); + mock.Setup(m => m.Execute(It.IsInRange(2, 20, Range.Exclusive))); + mock.Setup(m => m.Execute(3, "Caption")); + + mock.Object.Execute(3); + mock.Object.Execute(4); + mock.Object.Execute(5); + + var e = Assert.Throws(() => mock.Verify(m => m.Execute(0))); + Assert.Contains( + "\r\nConfigured setups:" + + "\r\nm => m.Execute(1), Times.Never" + + "\r\nm => m.Execute(It.IsInRange(2, 20, Range.Exclusive)), Times.Exactly(3)", + e.Message); + } + + [Fact] + public void TestGeneric() + { + var mock = new Mock(); + mock.Setup(m => m.Execute(1, 10)); + mock.Setup(m => m.Execute(1, "Foo")); + + mock.Object.Execute(1, 10); + + var e = Assert.Throws(() => mock.Verify(m => m.Execute(1, 1))); + Assert.Contains( + "\r\nConfigured setups:\r\nm => m.Execute(1, 10), Times.Once", + e.Message); + } + + [Fact] + public void TestNoSetups() + { + var mock = new Mock(); + + var e = Assert.Throws(() => mock.Verify(m => m.Execute(1))); + Assert.Contains("\r\nNo setups configured.", e.Message); + + } + + public interface IFoo + { + void Execute(int param); + void Execute(int param, string caption); + void Execute(int p, T param); + } + } + + #endregion + + #region #186 + + public class _186 + { + [Fact] + public void TestVerifyMessage() + { + var mock = new Mock(); + mock.Setup(m => m.OnExecute()); + + var e = Assert.Throws(() => mock.Verify(m => m.Execute())); + Assert.True(e.Message.StartsWith("Invalid verify")); + } + + public class Foo + { + public void Execute() + { + this.OnExecute(); + } + + public virtual void OnExecute() + { + throw new NotImplementedException(); + } + } + } + + #endregion + + #region #190 + + public class _190 + { + [Fact] + public void Test() + { + var mock = new Mock().As(); + mock.SetupAllProperties(); + + ISite site = new FooSite(); + mock.Object.Site = site; + Assert.Same(site, mock.Object.Site); + } + + public class FooSite : ISite + { + public IComponent Component + { + get { throw new NotImplementedException(); } + } + + public IContainer Container + { + get { throw new NotImplementedException(); } + } + + public bool DesignMode + { + get { throw new NotImplementedException(); } + } + + public string Name + { + get { throw new NotImplementedException(); } + set { throw new NotImplementedException(); } + } + + public object GetService(Type serviceType) + { + throw new NotImplementedException(); + } + } + + } + + #endregion + + #region #204 + + public class _204 + { + [Fact] + public void Test() + { + var mock = new Mock(); + mock.Setup(x => x.Select(u => u.Id == 100)) + .Returns(new User() { Id = 100 }); + + var user = mock.Object.Select(usr => usr.Id == 100); + Assert.Equal(100, user.Id); + mock.Verify(x => x.Select(usr => usr.Id == 100), Times.Once()); + + user = mock.Object.Select(usr => usr.Id == 101); + Assert.Null(user); + mock.Verify(x => x.Select(usr => usr.Id == 101), Times.Once()); + + mock.Verify(x => x.Select(usr => usr.Id == 102), Times.Never()); + mock.Verify(x => x.Select(It.IsAny>>()), Times.Exactly(2)); + } + + public interface IRepository + { + T Select(Expression> filter) where T : class; + } + + public class User + { + public int Id { get; set; } + } + } + + #endregion + + #region #205 + + public class _205 + { + [Fact] + public void Test() + { + new Mock().SetupAllProperties(); + } + + public interface IFoo + { + string Error { get; set; } + string this[int index] { get; set; } + } + } + + #endregion + + #region #223 + + public class _223 + { + [Fact] + public void TestSetup() + { + this.TestSetupHelper(); + } + + public void TestSetupHelper() where T : class, IFoo + { + var expected = 2; + + var target = new Mock(); + target.Setup(p => p.DoInt32(0)).Returns(expected); + target.Setup(p => p.DoGeneric(0)).Returns(expected); + + Assert.Equal(expected, target.Object.DoInt32(0)); + Assert.Equal(expected, target.Object.DoGeneric(0)); + } + + public interface IFoo + { + int DoInt32(int value); + T DoGeneric(int value); + } + + public class Foo : IFoo + { + public virtual int DoInt32(int value) + { + return 4; + } + + public virtual int DoGeneric(int value) + { + return 5; + } + } + } + + #endregion + + #region #228 + + public class _228 + { + [Fact] + public void Test() + { + var mock = new Mock() { CallBase = true }; + IFoo foo = mock.Object; + IBar bar = mock.Object; + + bool fooRaised = false; + bool barRaised = false; + foo.Foo += (s, e) => fooRaised = true; + bar.Bar += (s, e) => barRaised = true; + + mock.Object.RaiseMyEvents(); + + Assert.True(fooRaised); + Assert.True(barRaised); + } + + public interface IFoo + { + event EventHandler Foo; + } + + public interface IBar + { + event EventHandler Bar; + } + + public class FooBar : IFoo, IBar + { + public event EventHandler Foo; + public event EventHandler Bar; + + public void RaiseMyEvents() + { + if (this.Foo != null) + { + this.Foo(this, EventArgs.Empty); + } + if (this.Bar != null) + { + this.Bar(this, EventArgs.Empty); + } + } + } + } + + #endregion + + #region #229 + + public class _229 + { + [Fact] + public void Test() + { + var target = new Mock { CallBase = true }; + + var raised = false; + target.Object.MyEvent += (s, e) => raised = true; + target.Object.RaiseMyEvent(); + + Assert.True(raised); + } + + public class Foo + { + public virtual event EventHandler MyEvent; + + public void RaiseMyEvent() + { + if (this.MyEvent != null) + { + this.MyEvent(this, EventArgs.Empty); + } + } + } + } + + #endregion + + #region #230 + + public class _230 + { + [Fact] + public void ByteArrayCallbackArgumentShouldNotBeNull() + { + var data = new byte[] { 2, 1, 2 }; + var stream = new Mock(); + + stream.SetupGet(m => m.Length) + .Returns(data.Length); + stream.Setup(m => m.Read(It.IsAny(), It.IsAny(), It.IsAny())) + .Callback((b, o, c) => data.CopyTo(b, 0)) + .Returns(data.Length); + + var contents = new byte[stream.Object.Length]; + stream.Object.Read(contents, 0, (int)stream.Object.Length); + } + } + + #endregion + + #region #232 + + public class _232 + { + [Fact] + public void Test() + { + var repository = new Mock(); + var svc = new Service(repository.Object); + + svc.Create(); + + repository.Verify(r => r.Insert(It.IsAny()), Times.Once()); + repository.Verify(r => r.Insert(It.IsAny()), Times.Once()); + repository.Verify(r => r.Insert(It.IsAny()), Times.Exactly(2)); + } + + public interface IRepository + { + void Insert(IEntity entity); + } + + public interface IEntity + { + } + + public class Foo : IEntity + { + } + + public class Bar : IEntity + { + } + + public class Service + { + private IRepository repository; + + public Service(IRepository repository) + { + this.repository = repository; + } + + public void Create() + { + repository.Insert(new Foo()); + repository.Insert(new Bar()); + } + } + } + + #endregion + + #region #242 + + public class _242 + { + [Fact] + public void PropertyChangedTest() + { + var mock = new Mock(); + int callbacks = 0; + mock.Object.PropertyChanged += (sender, args) => callbacks++; + + mock.Raise(m => m.PropertyChanged += null, new PropertyChangedEventArgs("Foo")); + Assert.Equal(1, callbacks); + } + + public class PropertyChangedBase : INotifyPropertyChanged + { + public virtual event PropertyChangedEventHandler PropertyChanged = (s, e) => { }; + } + + public class PropertyChangedInherited : PropertyChangedBase + { + } + } + + #endregion + + #region #245 + + public class _245 + { + [Fact] + public void Test() + { + var mock = new Mock(); + + ITest instance; + instance = mock.Object; + } + + public interface ITest + { + void Do() where T2 : T1; + } + } + + #endregion + + #region #251 + + public class _251 + { + [Fact] + public void Test() + { + var repositoryMock = new Mock>(); + + var repository = repositoryMock.Object; + repository.Save("test"); + + repositoryMock.Verify(m => m.Save("test")); + } + + public interface IRepository + { + void Save(string value); + } + + public interface IRepository : IRepository + { + void Save(T value); + } + } + + #endregion + + #region #256 + + public class _256 + { + [Fact] + public void TestFinalizeNotMocked() + { + var mock = new Mock(MockBehavior.Strict); + mock.Setup(m => m.Foo).Returns(10); + mock.Setup(m => m.Bar).Returns("Hello mocked world!"); + var instance = mock.Object; + + Assert.Equal(10, instance.Foo); + } + + public class ClassWithFinalizer + { + public virtual int Foo { get; set; } + public virtual string Bar { get; set; } + + ~ClassWithFinalizer() + { + + } + } + } + + #endregion + + #region #261 + + public class _261 + { + [Fact] + public void Test() + { + var mock = new Mock(); + mock.Protected().SetupSet("Status", 42); + + mock.Object.SetStatus(42); + + mock.Protected().VerifySet("Status", Times.Once(), 42); + } + + public class Foo + { + public virtual int Status { get; protected set; } + + internal void SetStatus(int value) + { + this.Status = value; + } + } + } + + #endregion + + #region #267 + + public class _267 + { + public interface IPerformOperation + { + string Operation(object input); + } + + public class OperationUser + { + private readonly IPerformOperation m_OperationPerformer; + + public OperationUser(IPerformOperation operationPerformer) + { + m_OperationPerformer = operationPerformer; + } + + public string DoOperation(object input) + { + return m_OperationPerformer.Operation(input); + } + } + + public class HelperSetup + { + private Mock m_OperationStub; + + public HelperSetup() + { + m_OperationStub = new Mock(); + } + + [Fact] + public void InlineSetupTest() + { + m_OperationStub.Setup(m => m.Operation(It.IsAny())).Returns(value => "test"); + m_OperationStub.Setup(m => m.Operation(It.IsAny())).Returns(value => "25"); + + var operationUser = new OperationUser(m_OperationStub.Object); + + var intOperationResult = operationUser.DoOperation(9); + var stringOperationResult = operationUser.DoOperation("Hello"); + + Assert.Equal("25", intOperationResult); + Assert.Equal("test", stringOperationResult); + } + + [Fact] + public void HelperSetupTest() + { + SetupOperationStub(value => "test"); + SetupOperationStub(value => "25"); + + var operationUser = new OperationUser(m_OperationStub.Object); + + var intOperationResult = operationUser.DoOperation(9); + var stringOperationResult = operationUser.DoOperation("Hello"); + + Assert.Equal("25", intOperationResult); + Assert.Equal("test", stringOperationResult); + } + + private void SetupOperationStub(Func valueFunction) + { + m_OperationStub.Setup(m => m.Operation(It.IsAny())).Returns(valueFunction); + } + } + } + + #endregion + + #region #273 + + public class _273 + { + [Fact] + public void WhenMockingAnExternalInterface_ThenItWorks() + { + Assert.NotNull(new Mock().Object); + Assert.NotNull(Mock.Of()); + Assert.NotNull(new Mock().Object); + Assert.NotNull(new Mock().Object); + Assert.NotNull(Mock.Of()); + Assert.NotNull(new Mock().Object); + Assert.NotNull(new Mock().Object); + } + + public class Baz : ClassLibrary2.Bar + { + } + } + + #endregion + + #region #325 + + public class _325 + { + [Fact] + public void SubscribingWorks() + { + var target = new Mock { CallBase = true }; + target.As(); + + var bar = (IBar)target.Object; + var raised = false; + bar.SomeEvent += (sender, e) => raised = true; + + target.As().Raise(b => b.SomeEvent += null, EventArgs.Empty); + + Assert.True(raised); + } + + [Fact] + public void UnsubscribingWorks() + { + var target = new Mock { CallBase = true }; + target.As(); + + var bar = (IBar)target.Object; + var raised = false; + EventHandler handler = (sender, e) => raised = true; + bar.SomeEvent += handler; + bar.SomeEvent -= handler; + + target.As().Raise(b => b.SomeEvent += null, EventArgs.Empty); + + Assert.False(raised); + } + + public class Foo + { + } + + public interface IBar + { + event EventHandler SomeEvent; + } + + } + + #endregion + + #region #326 + +#if !NETCORE + + public class _326 + { + [Fact] + public void ShouldSupportMockingWinFormsControl() + { + var foo = new Mock(); + var bar = foo.Object; + } + } + +#endif + + #endregion + + #region Recursive issue + + public class RecursiveFixture + { + [Fact] + public void TestRecursive() + { + var mock = new Mock() { DefaultValue = DefaultValue.Mock }; + mock.Setup(c => c.HttpContext.Response.Write("stuff")); + + mock.Object.HttpContext.Response.Write("stuff"); + mock.Object.HttpContext.Response.ShouldEncode = true; + + Assert.Throws(() => mock.VerifySet( + c => c.HttpContext.Response.ShouldEncode = It.IsAny(), + Times.Never())); + } + + public class ControllerContext + { + public virtual HttpContext HttpContext { get; set; } + } + + public abstract class HttpContext + { + protected HttpContext() + { + } + + public virtual HttpResponse Response + { + get { throw new NotImplementedException(); } + } + } + + public abstract class HttpResponse + { + protected HttpResponse() + { + } + + public virtual bool ShouldEncode + { + get { throw new NotImplementedException(); } + set { throw new NotImplementedException(); } + } + + public virtual void Write(string s) + { + throw new NotImplementedException(); + } + } + } + + #endregion + + #region #250 + + public class _250 + { + [Fact] + public void Test() + { + var target = new Mock(); + + Assert.NotNull(target.Object); + } + } + + #endregion + + #region Matcher should work with Convert + + public class MatcherConvertFixture + { + public interface IFoo + { + string M(long l); + } + + [Fact] + public void MatcherDoesNotIgnoreConvert() + { + var mock = new Mock(MockBehavior.Strict); + mock.Setup(x => x.M(int.Parse("2"))).Returns("OK"); + Assert.Equal("OK", mock.Object.M(2L)); + } + } + + #endregion + } } diff --git a/UnitTests/ReturnsExtensionsFixture.cs b/UnitTests/ReturnsExtensionsFixture.cs index be2c630ee..859197bc5 100644 --- a/UnitTests/ReturnsExtensionsFixture.cs +++ b/UnitTests/ReturnsExtensionsFixture.cs @@ -5,98 +5,98 @@ namespace Moq.Tests { - public class ReturnsExtensionsFixture - { - public interface IAsyncInterface - { - Task NoParametersNonGenericTaskReturnType(); + public class ReturnsExtensionsFixture + { + public interface IAsyncInterface + { + Task NoParametersNonGenericTaskReturnType(); - Task NoParametersRefReturnType(); - - Task NoParametersValueReturnType(); + Task NoParametersRefReturnType(); - Task RefParameterRefReturnType(string value); - - Task RefParameterValueReturnType(string value); + Task NoParametersValueReturnType(); - Task ValueParameterRefReturnType(int value); - - Task ValueParameterValueReturnType(int value); + Task RefParameterRefReturnType(string value); - Task NewGuidAsync(); - } + Task RefParameterValueReturnType(string value); - [Fact] - public void ReturnsAsync_on_NoParametersRefReturnType() - { - var mock = new Mock(); - mock.Setup(x => x.NoParametersRefReturnType()).ReturnsAsync("TestString"); + Task ValueParameterRefReturnType(int value); - var task = mock.Object.NoParametersRefReturnType(); + Task ValueParameterValueReturnType(int value); - Assert.True(task.IsCompleted); - Assert.Equal("TestString", task.Result); - } + Task NewGuidAsync(); + } - [Fact] - public void ReturnsAsync_on_NoParametersValueReturnType() - { - var mock = new Mock(); - mock.Setup(x => x.NoParametersValueReturnType()).ReturnsAsync(36); + [Fact] + public void ReturnsAsync_on_NoParametersRefReturnType() + { + var mock = new Mock(); + mock.Setup(x => x.NoParametersRefReturnType()).ReturnsAsync("TestString"); - var task = mock.Object.NoParametersValueReturnType(); + var task = mock.Object.NoParametersRefReturnType(); - Assert.True(task.IsCompleted); - Assert.Equal(36, task.Result); - } + Assert.True(task.IsCompleted); + Assert.Equal("TestString", task.Result); + } - [Fact] - public void ReturnsAsync_on_RefParameterRefReturnType() - { - var mock = new Mock(); - mock.Setup(x => x.RefParameterRefReturnType("Param1")).ReturnsAsync("TestString"); + [Fact] + public void ReturnsAsync_on_NoParametersValueReturnType() + { + var mock = new Mock(); + mock.Setup(x => x.NoParametersValueReturnType()).ReturnsAsync(36); - var task = mock.Object.RefParameterRefReturnType("Param1"); + var task = mock.Object.NoParametersValueReturnType(); - Assert.True(task.IsCompleted); - Assert.Equal("TestString", task.Result); - } + Assert.True(task.IsCompleted); + Assert.Equal(36, task.Result); + } - [Fact] - public void ReturnsAsync_on_RefParameterValueReturnType() - { - var mock = new Mock(); - mock.Setup(x => x.RefParameterValueReturnType("Param1")).ReturnsAsync(36); + [Fact] + public void ReturnsAsync_on_RefParameterRefReturnType() + { + var mock = new Mock(); + mock.Setup(x => x.RefParameterRefReturnType("Param1")).ReturnsAsync("TestString"); - var task = mock.Object.RefParameterValueReturnType("Param1"); + var task = mock.Object.RefParameterRefReturnType("Param1"); - Assert.True(task.IsCompleted); - Assert.Equal(36, task.Result); - } + Assert.True(task.IsCompleted); + Assert.Equal("TestString", task.Result); + } + + [Fact] + public void ReturnsAsync_on_RefParameterValueReturnType() + { + var mock = new Mock(); + mock.Setup(x => x.RefParameterValueReturnType("Param1")).ReturnsAsync(36); + + var task = mock.Object.RefParameterValueReturnType("Param1"); + + Assert.True(task.IsCompleted); + Assert.Equal(36, task.Result); + } - [Fact] - public void ReturnsAsync_on_ValueParameterRefReturnType() - { - var mock = new Mock(); - mock.Setup(x => x.ValueParameterRefReturnType(36)).ReturnsAsync("TestString"); + [Fact] + public void ReturnsAsync_on_ValueParameterRefReturnType() + { + var mock = new Mock(); + mock.Setup(x => x.ValueParameterRefReturnType(36)).ReturnsAsync("TestString"); - var task = mock.Object.ValueParameterRefReturnType(36); + var task = mock.Object.ValueParameterRefReturnType(36); - Assert.True(task.IsCompleted); - Assert.Equal("TestString", task.Result); - } + Assert.True(task.IsCompleted); + Assert.Equal("TestString", task.Result); + } - [Fact] - public void ReturnsAsync_on_ValueParameterValueReturnType() - { - var mock = new Mock(); - mock.Setup(x => x.ValueParameterValueReturnType(36)).ReturnsAsync(37); + [Fact] + public void ReturnsAsync_on_ValueParameterValueReturnType() + { + var mock = new Mock(); + mock.Setup(x => x.ValueParameterValueReturnType(36)).ReturnsAsync(37); - var task = mock.Object.ValueParameterValueReturnType(36); + var task = mock.Object.ValueParameterValueReturnType(36); - Assert.True(task.IsCompleted); - Assert.Equal(37, task.Result); - } + Assert.True(task.IsCompleted); + Assert.Equal(37, task.Result); + } [Fact] public void ReturnsAsyncFunc_on_NoParametersRefReturnType() @@ -170,295 +170,295 @@ public void ReturnsAsyncFunc_on_ValueParameterValueReturnType() Assert.Equal(37, task.Result); } - [Fact] - public void ReturnsAsyncFunc_onEachInvocation_ValueReturnTypeLazyEvaluation() - { - var mock = new Mock(); - mock.Setup(x => x.NewGuidAsync()).ReturnsAsync(Guid.NewGuid); - - Guid firstEvaluationResult = mock.Object.NewGuidAsync().Result; - Guid secondEvaluationResult = mock.Object.NewGuidAsync().Result; + [Fact] + public void ReturnsAsyncFunc_onEachInvocation_ValueReturnTypeLazyEvaluation() + { + var mock = new Mock(); + mock.Setup(x => x.NewGuidAsync()).ReturnsAsync(Guid.NewGuid); - Assert.NotEqual(firstEvaluationResult, secondEvaluationResult); - } + Guid firstEvaluationResult = mock.Object.NewGuidAsync().Result; + Guid secondEvaluationResult = mock.Object.NewGuidAsync().Result; - [Fact] - public void ReturnsAsyncFunc_onEachInvocation_RefReturnTypeLazyEvaluation() - { - var mock = new Mock(); - mock.Setup(x => x.ValueParameterRefReturnType(36)).ReturnsAsync(() => new string(new[] { 'M', 'o', 'q', '4' })); - - string firstEvaluationResult = mock.Object.ValueParameterRefReturnType(36).Result; - string secondEvaluationResult = mock.Object.ValueParameterRefReturnType(36).Result; - - Assert.NotSame(firstEvaluationResult, secondEvaluationResult); - } - - [Fact] - public void ThrowsAsync_on_NoParametersNonGenericTaskReturnType() - { - var mock = new Mock(); - var exception = new InvalidOperationException(); - mock.Setup(x => x.NoParametersNonGenericTaskReturnType()).ThrowsAsync(exception); - - var task = mock.Object.NoParametersNonGenericTaskReturnType(); - - Assert.True(task.IsFaulted); - Assert.Equal(exception, task.Exception.InnerException); - } - - [Fact] - public void ThrowsAsync_on_NoParametersRefReturnType() - { - var mock = new Mock(); - var exception = new InvalidOperationException(); - mock.Setup(x => x.NoParametersRefReturnType()).ThrowsAsync(exception); - - var task = mock.Object.NoParametersRefReturnType(); - - Assert.True(task.IsFaulted); - Assert.Equal(exception, task.Exception.InnerException); - } - - [Fact] - public void ThrowsAsync_on_NoParametersValueReturnType() - { - var mock = new Mock(); - var exception = new InvalidOperationException(); - mock.Setup(x => x.NoParametersValueReturnType()).ThrowsAsync(exception); - - var task = mock.Object.NoParametersValueReturnType(); - - Assert.True(task.IsFaulted); - Assert.Equal(exception, task.Exception.InnerException); - } - - [Fact] - public void ThrowsAsync_on_RefParameterRefReturnType() - { - var mock = new Mock(); - var exception = new InvalidOperationException(); - mock.Setup(x => x.RefParameterRefReturnType("Param1")).ThrowsAsync(exception); - - var task = mock.Object.RefParameterRefReturnType("Param1"); - - Assert.True(task.IsFaulted); - Assert.Equal(exception, task.Exception.InnerException); - } - - [Fact] - public void ThrowsAsync_on_RefParameterValueReturnType() - { - var mock = new Mock(); - var exception = new InvalidOperationException(); - mock.Setup(x => x.RefParameterValueReturnType("Param1")).ThrowsAsync(exception); - - var task = mock.Object.RefParameterValueReturnType("Param1"); - - Assert.True(task.IsFaulted); - Assert.Equal(exception, task.Exception.InnerException); - } - - [Fact] - public void ThrowsAsync_on_ValueParameterRefReturnType() - { - var mock = new Mock(); - var exception = new InvalidOperationException(); - mock.Setup(x => x.ValueParameterRefReturnType(36)).ThrowsAsync(exception); - - var task = mock.Object.ValueParameterRefReturnType(36); - - Assert.True(task.IsFaulted); - Assert.Equal(exception, task.Exception.InnerException); - } - - [Fact] - public void ThrowsAsync_on_ValueParameterValueReturnType() - { - var mock = new Mock(); - var exception = new InvalidOperationException(); - mock.Setup(x => x.ValueParameterValueReturnType(36)).ThrowsAsync(exception); - - var task = mock.Object.ValueParameterValueReturnType(36); - - Assert.True(task.IsFaulted); - Assert.Equal(exception, task.Exception.InnerException); - } - - // The test below is dependent on the timings (too much of a 'works-on-my-machine' smell) - //[Theory] - //[InlineData(true)] - //[InlineData(false)] - //public async Task ReturnsAsyncWithDelayTriggersRealAsyncBehaviour(bool useDelay) - //{ - // var mock = new Mock(); - - // var setup = mock.Setup(x => x.RefParameterValueReturnType("test")); - - // if (useDelay) - // setup.ReturnsAsync(5, TimeSpan.FromMilliseconds(1)); - // else - // setup.ReturnsAsync(5); - - // var thread1 = Thread.CurrentThread; - // await mock.Object.RefParameterValueReturnType("test"); - // var thread2 = Thread.CurrentThread; - - // if (useDelay) - // Assert.NotEqual(thread1, thread2); - // else - // Assert.Equal(thread1, thread2); - //} - - [Fact] - public void ReturnsAsyncWithDelayDoesNotImmediatelyComplete() - { - var longEnoughForAnyBuildServer = TimeSpan.FromSeconds(5); - - var mock = new Mock(); - mock.Setup(x => x.RefParameterValueReturnType("test")).ReturnsAsync(5, longEnoughForAnyBuildServer); - - var task = mock.Object.RefParameterValueReturnType("test"); - - Assert.False(task.IsCompleted); - } - - [Theory] - [InlineData(-1, true)] - [InlineData(0, true)] - [InlineData(1, false)] - public void DelayMustBePositive(int ticks, bool mustThrow) - { - var mock = new Mock(); - - Action setup = () => mock - .Setup(x => x.RefParameterValueReturnType("test")) - .ReturnsAsync(5, TimeSpan.FromTicks(ticks)); + Assert.NotEqual(firstEvaluationResult, secondEvaluationResult); + } - if (mustThrow) - Assert.Throws(setup); - else - setup(); - } + [Fact] + public void ReturnsAsyncFunc_onEachInvocation_RefReturnTypeLazyEvaluation() + { + var mock = new Mock(); + mock.Setup(x => x.ValueParameterRefReturnType(36)).ReturnsAsync(() => new string(new[] { 'M', 'o', 'q', '4' })); + string firstEvaluationResult = mock.Object.ValueParameterRefReturnType(36).Result; + string secondEvaluationResult = mock.Object.ValueParameterRefReturnType(36).Result; - [Fact] - public async Task ReturnsAsyncWithDelayReturnsValue() - { - var mock = new Mock(); - mock.Setup(x => x.RefParameterValueReturnType("test")).ReturnsAsync(5, TimeSpan.FromMilliseconds(1)); + Assert.NotSame(firstEvaluationResult, secondEvaluationResult); + } - var value = await mock.Object.RefParameterValueReturnType("test"); + [Fact] + public void ThrowsAsync_on_NoParametersNonGenericTaskReturnType() + { + var mock = new Mock(); + var exception = new InvalidOperationException(); + mock.Setup(x => x.NoParametersNonGenericTaskReturnType()).ThrowsAsync(exception); - Assert.Equal(5, value); - } + var task = mock.Object.NoParametersNonGenericTaskReturnType(); - [Fact] - public async Task ReturnsAsyncWithMinAndMaxDelayReturnsValue() - { - var mock = new Mock(); - mock.Setup(x => x.RefParameterValueReturnType("test")).ReturnsAsync(5, TimeSpan.FromMilliseconds(1), TimeSpan.FromMilliseconds(2)); + Assert.True(task.IsFaulted); + Assert.Equal(exception, task.Exception.InnerException); + } - var value = await mock.Object.RefParameterValueReturnType("test"); + [Fact] + public void ThrowsAsync_on_NoParametersRefReturnType() + { + var mock = new Mock(); + var exception = new InvalidOperationException(); + mock.Setup(x => x.NoParametersRefReturnType()).ThrowsAsync(exception); - Assert.Equal(5, value); - } + var task = mock.Object.NoParametersRefReturnType(); - [Fact] - public async Task ReturnsAsyncWithMinAndMaxDelayAndOwnRandomGeneratorReturnsValue() - { - var mock = new Mock(); - mock.Setup(x => x.RefParameterValueReturnType("test")).ReturnsAsync(5, TimeSpan.FromMilliseconds(1), TimeSpan.FromMilliseconds(2), new Random()); + Assert.True(task.IsFaulted); + Assert.Equal(exception, task.Exception.InnerException); + } - var value = await mock.Object.RefParameterValueReturnType("test"); + [Fact] + public void ThrowsAsync_on_NoParametersValueReturnType() + { + var mock = new Mock(); + var exception = new InvalidOperationException(); + mock.Setup(x => x.NoParametersValueReturnType()).ThrowsAsync(exception); - Assert.Equal(5, value); - } + var task = mock.Object.NoParametersValueReturnType(); - [Fact] - public async Task ReturnsAsyncWithNullRandomGenerator() - { - var mock = new Mock(); + Assert.True(task.IsFaulted); + Assert.Equal(exception, task.Exception.InnerException); + } - Action setup = () => mock - .Setup(x => x.RefParameterValueReturnType("test")) - .ReturnsAsync(5, TimeSpan.FromMilliseconds(1), TimeSpan.FromMilliseconds(2), null); + [Fact] + public void ThrowsAsync_on_RefParameterRefReturnType() + { + var mock = new Mock(); + var exception = new InvalidOperationException(); + mock.Setup(x => x.RefParameterRefReturnType("Param1")).ThrowsAsync(exception); - var paramName = Assert.Throws(setup).ParamName; - Assert.Equal("random", paramName); - } + var task = mock.Object.RefParameterRefReturnType("Param1"); - [Fact] - public async Task ThrowsWithDelay() - { - var mock = new Mock(); + Assert.True(task.IsFaulted); + Assert.Equal(exception, task.Exception.InnerException); + } - mock - .Setup(x => x.RefParameterValueReturnType("test")) - .ThrowsAsync(new ArithmeticException("yikes"), TimeSpan.FromMilliseconds(1)); + [Fact] + public void ThrowsAsync_on_RefParameterValueReturnType() + { + var mock = new Mock(); + var exception = new InvalidOperationException(); + mock.Setup(x => x.RefParameterValueReturnType("Param1")).ThrowsAsync(exception); - Func> test = () => mock.Object.RefParameterValueReturnType("test"); + var task = mock.Object.RefParameterValueReturnType("Param1"); - var exception = await Assert.ThrowsAsync(test); - Assert.Equal("yikes", exception.Message); - } + Assert.True(task.IsFaulted); + Assert.Equal(exception, task.Exception.InnerException); + } - [Fact] - public async Task ThrowsWithRandomDelay() - { - var mock = new Mock(); + [Fact] + public void ThrowsAsync_on_ValueParameterRefReturnType() + { + var mock = new Mock(); + var exception = new InvalidOperationException(); + mock.Setup(x => x.ValueParameterRefReturnType(36)).ThrowsAsync(exception); - var minDelay = TimeSpan.FromMilliseconds(1); - var maxDelay = TimeSpan.FromMilliseconds(2); + var task = mock.Object.ValueParameterRefReturnType(36); - mock - .Setup(x => x.RefParameterValueReturnType("test")) - .ThrowsAsync(new ArithmeticException("yikes"), minDelay, maxDelay); + Assert.True(task.IsFaulted); + Assert.Equal(exception, task.Exception.InnerException); + } - Func> test = () => mock.Object.RefParameterValueReturnType("test"); + [Fact] + public void ThrowsAsync_on_ValueParameterValueReturnType() + { + var mock = new Mock(); + var exception = new InvalidOperationException(); + mock.Setup(x => x.ValueParameterValueReturnType(36)).ThrowsAsync(exception); - var exception = await Assert.ThrowsAsync(test); - Assert.Equal("yikes", exception.Message); - } + var task = mock.Object.ValueParameterValueReturnType(36); - [Fact] - public async Task ThrowsWithRandomDelayAndOwnRandomGenerator() - { - var mock = new Mock(); + Assert.True(task.IsFaulted); + Assert.Equal(exception, task.Exception.InnerException); + } - var minDelay = TimeSpan.FromMilliseconds(1); - var maxDelay = TimeSpan.FromMilliseconds(2); + // The test below is dependent on the timings (too much of a 'works-on-my-machine' smell) + //[Theory] + //[InlineData(true)] + //[InlineData(false)] + //public async Task ReturnsAsyncWithDelayTriggersRealAsyncBehaviour(bool useDelay) + //{ + // var mock = new Mock(); - mock - .Setup(x => x.RefParameterValueReturnType("test")) - .ThrowsAsync(new ArithmeticException("yikes"), minDelay, maxDelay, new Random()); + // var setup = mock.Setup(x => x.RefParameterValueReturnType("test")); - Func> test = () => mock.Object.RefParameterValueReturnType("test"); + // if (useDelay) + // setup.ReturnsAsync(5, TimeSpan.FromMilliseconds(1)); + // else + // setup.ReturnsAsync(5); - var exception = await Assert.ThrowsAsync(test); - Assert.Equal("yikes", exception.Message); - } + // var thread1 = Thread.CurrentThread; + // await mock.Object.RefParameterValueReturnType("test"); + // var thread2 = Thread.CurrentThread; + // if (useDelay) + // Assert.NotEqual(thread1, thread2); + // else + // Assert.Equal(thread1, thread2); + //} - [Fact] - public async Task ThrowsAsyncWithNullRandomGenerator() - { - var mock = new Mock(); + [Fact] + public void ReturnsAsyncWithDelayDoesNotImmediatelyComplete() + { + var longEnoughForAnyBuildServer = TimeSpan.FromSeconds(5); - Action setup = () => - { - var anyException = new Exception(); - var minDelay = TimeSpan.FromMilliseconds(1); - var maxDelay = TimeSpan.FromMilliseconds(2); + var mock = new Mock(); + mock.Setup(x => x.RefParameterValueReturnType("test")).ReturnsAsync(5, longEnoughForAnyBuildServer); - mock - .Setup(x => x.RefParameterValueReturnType("test")) - .ThrowsAsync(anyException, minDelay, maxDelay, null); - }; + var task = mock.Object.RefParameterValueReturnType("test"); - var paramName = Assert.Throws(setup).ParamName; - Assert.Equal("random", paramName); - } + Assert.False(task.IsCompleted); + } + + [Theory] + [InlineData(-1, true)] + [InlineData(0, true)] + [InlineData(1, false)] + public void DelayMustBePositive(int ticks, bool mustThrow) + { + var mock = new Mock(); + + Action setup = () => mock + .Setup(x => x.RefParameterValueReturnType("test")) + .ReturnsAsync(5, TimeSpan.FromTicks(ticks)); + + if (mustThrow) + Assert.Throws(setup); + else + setup(); + } + + + [Fact] + public async Task ReturnsAsyncWithDelayReturnsValue() + { + var mock = new Mock(); + mock.Setup(x => x.RefParameterValueReturnType("test")).ReturnsAsync(5, TimeSpan.FromMilliseconds(1)); + + var value = await mock.Object.RefParameterValueReturnType("test"); + + Assert.Equal(5, value); + } + + [Fact] + public async Task ReturnsAsyncWithMinAndMaxDelayReturnsValue() + { + var mock = new Mock(); + mock.Setup(x => x.RefParameterValueReturnType("test")).ReturnsAsync(5, TimeSpan.FromMilliseconds(1), TimeSpan.FromMilliseconds(2)); + + var value = await mock.Object.RefParameterValueReturnType("test"); + + Assert.Equal(5, value); + } + + [Fact] + public async Task ReturnsAsyncWithMinAndMaxDelayAndOwnRandomGeneratorReturnsValue() + { + var mock = new Mock(); + mock.Setup(x => x.RefParameterValueReturnType("test")).ReturnsAsync(5, TimeSpan.FromMilliseconds(1), TimeSpan.FromMilliseconds(2), new Random()); + + var value = await mock.Object.RefParameterValueReturnType("test"); + + Assert.Equal(5, value); + } + + [Fact] + public async Task ReturnsAsyncWithNullRandomGenerator() + { + var mock = new Mock(); + + Action setup = () => mock + .Setup(x => x.RefParameterValueReturnType("test")) + .ReturnsAsync(5, TimeSpan.FromMilliseconds(1), TimeSpan.FromMilliseconds(2), null); + + var paramName = Assert.Throws(setup).ParamName; + Assert.Equal("random", paramName); + } + + [Fact] + public async Task ThrowsWithDelay() + { + var mock = new Mock(); + + mock + .Setup(x => x.RefParameterValueReturnType("test")) + .ThrowsAsync(new ArithmeticException("yikes"), TimeSpan.FromMilliseconds(1)); + + Func> test = () => mock.Object.RefParameterValueReturnType("test"); + + var exception = await Assert.ThrowsAsync(test); + Assert.Equal("yikes", exception.Message); + } + + [Fact] + public async Task ThrowsWithRandomDelay() + { + var mock = new Mock(); + + var minDelay = TimeSpan.FromMilliseconds(1); + var maxDelay = TimeSpan.FromMilliseconds(2); + + mock + .Setup(x => x.RefParameterValueReturnType("test")) + .ThrowsAsync(new ArithmeticException("yikes"), minDelay, maxDelay); + + Func> test = () => mock.Object.RefParameterValueReturnType("test"); + + var exception = await Assert.ThrowsAsync(test); + Assert.Equal("yikes", exception.Message); + } + + [Fact] + public async Task ThrowsWithRandomDelayAndOwnRandomGenerator() + { + var mock = new Mock(); + + var minDelay = TimeSpan.FromMilliseconds(1); + var maxDelay = TimeSpan.FromMilliseconds(2); + + mock + .Setup(x => x.RefParameterValueReturnType("test")) + .ThrowsAsync(new ArithmeticException("yikes"), minDelay, maxDelay, new Random()); + + Func> test = () => mock.Object.RefParameterValueReturnType("test"); + + var exception = await Assert.ThrowsAsync(test); + Assert.Equal("yikes", exception.Message); + } + + + [Fact] + public async Task ThrowsAsyncWithNullRandomGenerator() + { + var mock = new Mock(); + + Action setup = () => + { + var anyException = new Exception(); + var minDelay = TimeSpan.FromMilliseconds(1); + var maxDelay = TimeSpan.FromMilliseconds(2); + + mock + .Setup(x => x.RefParameterValueReturnType("test")) + .ThrowsAsync(anyException, minDelay, maxDelay, null); + }; + + var paramName = Assert.Throws(setup).ParamName; + Assert.Equal("random", paramName); + } - } + } } diff --git a/UnitTests/SequenceExtensionsFixture.cs b/UnitTests/SequenceExtensionsFixture.cs index 2e4aaed8f..2ab591407 100644 --- a/UnitTests/SequenceExtensionsFixture.cs +++ b/UnitTests/SequenceExtensionsFixture.cs @@ -120,4 +120,4 @@ public virtual Task DoAsync() } } } -} \ No newline at end of file +} diff --git a/UnitTests/StubExtensionsFixture.cs b/UnitTests/StubExtensionsFixture.cs index cdd395053..b1f4b47df 100644 --- a/UnitTests/StubExtensionsFixture.cs +++ b/UnitTests/StubExtensionsFixture.cs @@ -58,15 +58,15 @@ public void StubsAllProperties() Assert.Same(bar.Object, mock.Object.Bar); } - [Fact] - public void StubsAllCyrcularDependency() - { - var mock = new Mock(); + [Fact] + public void StubsAllCyrcularDependency() + { + var mock = new Mock(); - mock.SetupAllProperties(); + mock.SetupAllProperties(); - Assert.Null(mock.Object.Hierarchy); - } + Assert.Null(mock.Object.Hierarchy); + } [Fact] public void StubsAllHierarchy() @@ -138,9 +138,9 @@ public interface IBaz : IBar string Name { get; set; } } - public interface IHierarchy - { - IHierarchy Hierarchy { get; set; } - } + public interface IHierarchy + { + IHierarchy Hierarchy { get; set; } + } } } diff --git a/UnitTests/TimesFixture.cs b/UnitTests/TimesFixture.cs index cffa8bedc..a6d4f42bb 100644 --- a/UnitTests/TimesFixture.cs +++ b/UnitTests/TimesFixture.cs @@ -168,4 +168,4 @@ public void OnceChecksOneTime() Assert.False(target.Verify(int.MaxValue)); } } -} \ No newline at end of file +} diff --git a/UnitTests/VerifyFixture.cs b/UnitTests/VerifyFixture.cs index c08e25e54..0587492ec 100644 --- a/UnitTests/VerifyFixture.cs +++ b/UnitTests/VerifyFixture.cs @@ -846,7 +846,7 @@ public void IncludesActualCallsInFailureMessage() mock.Object.Execute("ping"); mock.Object.Echo(42); mock.Object.Submit(); - mock.Object.Save(new object[] {1, 2, "hello"}); + mock.Object.Save(new object[] {1, 2, "hello"}); var mex = Assert.Throws(() => mock.Verify(f => f.Execute("pong"))); @@ -856,30 +856,30 @@ public void IncludesActualCallsInFailureMessage() "IFoo.Execute(\"ping\")" + Environment.NewLine + "IFoo.Echo(42)" + Environment.NewLine + "IFoo.Submit()" + Environment.NewLine + - "IFoo.Save([1, 2, \"hello\"])", + "IFoo.Save([1, 2, \"hello\"])", mex.Message); } - [Fact] - public void IncludesActualValuesFromVerifyNotVariableNames() - { - var expectedArg = "lorem,ipsum"; - var mock = new Moq.Mock(); + [Fact] + public void IncludesActualValuesFromVerifyNotVariableNames() + { + var expectedArg = "lorem,ipsum"; + var mock = new Moq.Mock(); - var mex = Assert.Throws(() => mock.Verify(f => f.Execute(expectedArg.Substring(0, 5)))); - Assert.Contains("f.Execute(\"lorem\")", mex.Message); - } + var mex = Assert.Throws(() => mock.Verify(f => f.Execute(expectedArg.Substring(0, 5)))); + Assert.Contains("f.Execute(\"lorem\")", mex.Message); + } - [Fact] - public void IncludesActualValuesFromSetups() - { - var expectedArg = "lorem,ipsum"; - var mock = new Moq.Mock(); - mock.Setup(f => f.Save(expectedArg.Substring(0, 5))); + [Fact] + public void IncludesActualValuesFromSetups() + { + var expectedArg = "lorem,ipsum"; + var mock = new Moq.Mock(); + mock.Setup(f => f.Save(expectedArg.Substring(0, 5))); - var mex = Assert.Throws(() => mock.Verify(foo => foo.Save("never"))); - Assert.Contains("f.Save(\"lorem\")", mex.Message); - } + var mex = Assert.Throws(() => mock.Verify(foo => foo.Save("never"))); + Assert.Contains("f.Save(\"lorem\")", mex.Message); + } [Fact] public void IncludesMessageAboutNoActualCallsInFailureMessage() @@ -901,29 +901,29 @@ public void IncludesMessageAboutNoSetupCallsInFailureMessage() Assert.Contains(Environment.NewLine + "No setups configured.", mex.Message); } - [Fact] - public void MatchesDerivedTypesForGenericTypes() - { - var mock = new Mock(); - mock.Object.Call(new BazParam()); - mock.Object.Call(new BazParam2()); - - mock.Verify(foo => foo.Call(It.IsAny()), Times.Exactly(2)); - } - - /// - /// Warning, this is a flaky test and doesn't fail when run as standalone. Running all tests at once will increase the chances of that test to fail. - /// - [Fact] - public void DoesNotThrowCollectionModifiedWhenMoreInvocationsInterceptedDuringVerfication() - { - var mock = new Mock(); - Parallel.For(0, 100, (i) => - { - mock.Object.Submit(); - mock.Verify(foo => foo.Submit()); - }); - } + [Fact] + public void MatchesDerivedTypesForGenericTypes() + { + var mock = new Mock(); + mock.Object.Call(new BazParam()); + mock.Object.Call(new BazParam2()); + + mock.Verify(foo => foo.Call(It.IsAny()), Times.Exactly(2)); + } + + /// + /// Warning, this is a flaky test and doesn't fail when run as standalone. Running all tests at once will increase the chances of that test to fail. + /// + [Fact] + public void DoesNotThrowCollectionModifiedWhenMoreInvocationsInterceptedDuringVerfication() + { + var mock = new Mock(); + Parallel.For(0, 100, (i) => + { + mock.Object.Submit(); + mock.Verify(foo => foo.Submit()); + }); + } public interface IBar { @@ -939,25 +939,25 @@ public interface IFoo int Echo(int value); void Submit(); string Execute(string command); - void Save(object o); + void Save(object o); } - public interface IBazParam - { - } + public interface IBazParam + { + } - public interface IBaz - { - void Call(T param) where T:IBazParam; - } + public interface IBaz + { + void Call(T param) where T:IBazParam; + } - public class BazParam:IBazParam - { - } + public class BazParam:IBazParam + { + } - public class BazParam2:BazParam - { - } + public class BazParam2:BazParam + { + } } } diff --git a/UnitTests/project.json b/UnitTests/project.json index 2ee5aadb0..4fc814998 100644 --- a/UnitTests/project.json +++ b/UnitTests/project.json @@ -1,13 +1,13 @@ { - "dependencies": { - "Castle.Core": "4.0.0", - "xunit": "2.1.0", - "xunit.runner.visualstudio": "2.1.0" - }, - "frameworks": { - "net45": {} - }, - "runtimes": { - "win": {} - } -} \ No newline at end of file + "dependencies": { + "Castle.Core": "4.0.0", + "xunit": "2.1.0", + "xunit.runner.visualstudio": "2.1.0" + }, + "frameworks": { + "net45": {} + }, + "runtimes": { + "win": {} + } +} diff --git a/Visualizer/CallViewModel.cs b/Visualizer/CallViewModel.cs index 6417c932d..0a88bafd1 100644 --- a/Visualizer/CallViewModel.cs +++ b/Visualizer/CallViewModel.cs @@ -117,4 +117,4 @@ private static string GetKind(ParameterViewModel a) throw new Exception(); } } -} \ No newline at end of file +} diff --git a/Visualizer/ContainerViewModel.cs b/Visualizer/ContainerViewModel.cs index d528522e6..20c70c7fe 100644 --- a/Visualizer/ContainerViewModel.cs +++ b/Visualizer/ContainerViewModel.cs @@ -27,4 +27,4 @@ public ContainerViewModel(string name, IEnumerable children) public IEnumerable Children { get; private set; } } -} \ No newline at end of file +} diff --git a/Visualizer/MockContextViewModel.cs b/Visualizer/MockContextViewModel.cs index 89720944e..00a0c28b2 100644 --- a/Visualizer/MockContextViewModel.cs +++ b/Visualizer/MockContextViewModel.cs @@ -81,4 +81,4 @@ private static CallViewModel GetSetupCall(CallViewModel call) return call; } } -} \ No newline at end of file +} diff --git a/Visualizer/MockViewModel.cs b/Visualizer/MockViewModel.cs index b92c1d29a..83c6a9454 100644 --- a/Visualizer/MockViewModel.cs +++ b/Visualizer/MockViewModel.cs @@ -18,4 +18,4 @@ internal MockViewModel(Type mockedType, params ContainerViewModel[] containers) public string MockedType { get; private set; } } -} \ No newline at end of file +} diff --git a/Visualizer/MockVisualizer.cs b/Visualizer/MockVisualizer.cs index df3a3058c..179b4f4e2 100644 --- a/Visualizer/MockVisualizer.cs +++ b/Visualizer/MockVisualizer.cs @@ -14,4 +14,4 @@ public class MockVisualizer : DialogDebuggerVisualizer } } } -} \ No newline at end of file +} diff --git a/Visualizer/MockVisualizerForm.Designer.cs b/Visualizer/MockVisualizerForm.Designer.cs index 0daaca086..77da73209 100644 --- a/Visualizer/MockVisualizerForm.Designer.cs +++ b/Visualizer/MockVisualizerForm.Designer.cs @@ -63,8 +63,5 @@ private void InitializeComponent() private System.Windows.Forms.Integration.ElementHost visualizerHost; private MockVisualizerView mockVisualizerView; - - - } -} \ No newline at end of file +} diff --git a/Visualizer/MockVisualizerForm.cs b/Visualizer/MockVisualizerForm.cs index e50961c99..deee167d4 100644 --- a/Visualizer/MockVisualizerForm.cs +++ b/Visualizer/MockVisualizerForm.cs @@ -10,4 +10,4 @@ public MockVisualizerForm(object context) this.visualizerHost.HostContainer.DataContext = context; } } -} \ No newline at end of file +} diff --git a/Visualizer/MockVisualizerForm.resx b/Visualizer/MockVisualizerForm.resx index 19dc0dd8b..18d0f9beb 100644 --- a/Visualizer/MockVisualizerForm.resx +++ b/Visualizer/MockVisualizerForm.resx @@ -1,120 +1,120 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - text/microsoft-resx - - - 2.0 - - - System.Resources.ResXResourceReader, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 - - - System.Resources.ResXResourceWriter, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 - - \ No newline at end of file + mimetype: application/x-microsoft.net.object.bytearray.base64 + value : The object must be serialized into a byte array + : using a System.ComponentModel.TypeConverter + : and then encoded with base64 encoding. + --> + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + text/microsoft-resx + + + 2.0 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + diff --git a/Visualizer/MockVisualizerObjectSource.cs b/Visualizer/MockVisualizerObjectSource.cs index 93fa33f85..88c763204 100644 --- a/Visualizer/MockVisualizerObjectSource.cs +++ b/Visualizer/MockVisualizerObjectSource.cs @@ -10,4 +10,4 @@ public override void GetData(object target, Stream outgoingData) VisualizerObjectSource.Serialize(outgoingData, new MockContextViewModel((Mock)target)); } } -} \ No newline at end of file +} diff --git a/Visualizer/MockVisualizerView.xaml b/Visualizer/MockVisualizerView.xaml index e699c1485..1ac820e5c 100644 --- a/Visualizer/MockVisualizerView.xaml +++ b/Visualizer/MockVisualizerView.xaml @@ -47,4 +47,4 @@ - \ No newline at end of file + diff --git a/Visualizer/MockVisualizerView.xaml.cs b/Visualizer/MockVisualizerView.xaml.cs index 236b93f94..766428528 100644 --- a/Visualizer/MockVisualizerView.xaml.cs +++ b/Visualizer/MockVisualizerView.xaml.cs @@ -2,11 +2,11 @@ namespace Moq.Visualizer { - public partial class MockVisualizerView : UserControl - { - public MockVisualizerView() - { - this.InitializeComponent(); - } - } -} \ No newline at end of file + public partial class MockVisualizerView : UserControl + { + public MockVisualizerView() + { + this.InitializeComponent(); + } + } +} diff --git a/Visualizer/Moq.Visualizer.csproj b/Visualizer/Moq.Visualizer.csproj index 701739d7b..e1c863311 100644 --- a/Visualizer/Moq.Visualizer.csproj +++ b/Visualizer/Moq.Visualizer.csproj @@ -1,167 +1,167 @@  - - Debug - AnyCPU - 9.0.30729 - 2.0 - {335EAF40-60EF-40D7-84A8-E33D255FA59F} - Library - Properties - Moq.Visualizer - Moq.Visualizer - v4.0 - 512 - true - ..\Moq.snk - - - 3.5 - - publish\ - true - Disk - false - Foreground - 7 - Days - false - false - true - 0 - 1.0.0.%2a - false - false - true - - - - true - full - false - bin\Debug\ - DEBUG;TRACE - prompt - 4 - AllRules.ruleset - - - pdbonly - true - bin\Release\ - TRACE - prompt - 4 - AllRules.ruleset - - - - - 3.0 - - - 3.0 - - - - 3.5 - - - - - - 3.5 - - - 3.0 - - - 3.0 - - - - - Form - - - MockVisualizerForm.cs - - - - - Code - - - - - - - - True - True - Resources.resx - - - - MockVisualizerView.xaml - - - - - Designer - MSBuild:Compile - MSBuild:Compile - Designer - - - - - Moq.snk - - - - - MockVisualizerForm.cs - - - ResXFileCodeGenerator - Resources.Designer.cs - - - - - False - .NET Framework 3.5 SP1 Client Profile - false - - - False - .NET Framework 3.5 SP1 - true - - - False - Microsoft Visual Basic PowerPacks 10.0 - true - - - False - Windows Installer 3.1 - true - - - - - {1C91AC30-5977-4BE5-BA67-8EB186C03514} - Moq - - - - - \ No newline at end of file + + Debug + AnyCPU + 9.0.30729 + 2.0 + {335EAF40-60EF-40D7-84A8-E33D255FA59F} + Library + Properties + Moq.Visualizer + Moq.Visualizer + v4.0 + 512 + true + ..\Moq.snk + + + 3.5 + + publish\ + true + Disk + false + Foreground + 7 + Days + false + false + true + 0 + 1.0.0.%2a + false + false + true + + + + true + full + false + bin\Debug\ + DEBUG;TRACE + prompt + 4 + AllRules.ruleset + + + pdbonly + true + bin\Release\ + TRACE + prompt + 4 + AllRules.ruleset + + + + + 3.0 + + + 3.0 + + + + 3.5 + + + + + + 3.5 + + + 3.0 + + + 3.0 + + + + + Form + + + MockVisualizerForm.cs + + + + + Code + + + + + + + + True + True + Resources.resx + + + + MockVisualizerView.xaml + + + + + Designer + MSBuild:Compile + MSBuild:Compile + Designer + + + + + Moq.snk + + + + + MockVisualizerForm.cs + + + ResXFileCodeGenerator + Resources.Designer.cs + + + + + False + .NET Framework 3.5 SP1 Client Profile + false + + + False + .NET Framework 3.5 SP1 + true + + + False + Microsoft Visual Basic PowerPacks 10.0 + true + + + False + Windows Installer 3.1 + true + + + + + {1C91AC30-5977-4BE5-BA67-8EB186C03514} + Moq + + + + + diff --git a/Visualizer/ParameterViewModel.cs b/Visualizer/ParameterViewModel.cs index 70da94df2..f696b4e03 100644 --- a/Visualizer/ParameterViewModel.cs +++ b/Visualizer/ParameterViewModel.cs @@ -28,4 +28,4 @@ public ParameterViewModel(ParameterInfo parameterInfo, object value) public object Value { get; private set; } } -} \ No newline at end of file +} diff --git a/Visualizer/SetupViewModel.cs b/Visualizer/SetupViewModel.cs index 9a9629785..c9ef4408e 100644 --- a/Visualizer/SetupViewModel.cs +++ b/Visualizer/SetupViewModel.cs @@ -31,4 +31,4 @@ public bool IsExpanded public string SetupExpression { get; private set; } } -} \ No newline at end of file +} diff --git a/build.cmd b/build.cmd index bb886b926..54764b457 100644 --- a/build.cmd +++ b/build.cmd @@ -39,4 +39,4 @@ echo Running "%msb%" build.proj /v:normal %1 %2 %3 %4 %5 %6 %7 %8 %9 POPD >NUL ENDLOCAL -ECHO ON \ No newline at end of file +ECHO ON diff --git a/build.proj b/build.proj index d106e1cb4..2bb3e1189 100644 --- a/build.proj +++ b/build.proj @@ -72,9 +72,9 @@ + Condition=" '$(Coverage)' == 'true' " + ConsoleToMSBuild="true" + ContinueOnError="ErrorAndContinue" /> @@ -84,8 +84,8 @@ + StandardErrorImportance="high" + StandardOutputImportance="normal" /> @@ -109,16 +109,16 @@ + Condition=" '$(PendingRestore)' == 'true' And '$(target)' != 'configure' "/> $(GitSemVerMajor).$(GitSemVerMinor).$(GitSemVerPatch)$(GitSemVerDashLabel) - - - + + +