├── .github ├── FUNDING.yml └── workflows │ └── build-test-publish.yml ├── .gitignore ├── EntityFrameworkCoreMock.sln ├── LICENSE ├── README.md ├── Signing.snk ├── src ├── Directory.Build.props ├── EntityFrameworkCoreMock.Moq │ ├── DbContextMock.cs │ ├── DbSetMock.cs │ ├── EntityFrameworkCoreMock.Moq.csproj │ └── _Visibility.cs ├── EntityFrameworkCoreMock.NSubstitute │ ├── DbContextMock.cs │ ├── DbSetMock.cs │ ├── EntityFrameworkCoreMock.NSubstitute.csproj │ └── _Visibility.cs └── EntityFrameworkCoreMock.Shared │ ├── CompositeKeyFactoryBuilder.cs │ ├── DbAsyncEnumerable.cs │ ├── DbAsyncEnumerator.cs │ ├── DbAsyncQueryProvider.cs │ ├── DbSetBackingStore.cs │ ├── EntityFrameworkCoreMock.Shared.csproj │ ├── IDbQueryMock.cs │ ├── IDbSetMock.cs │ ├── IKeyFactoryBuilder.cs │ ├── KeyContext.cs │ ├── KeyFactoryBuilders │ ├── AttributeBasedKeyFactoryBuilder.cs │ ├── ConventionBasedKeyFactoryBuilder.cs │ └── KeyFactoryBuilderBase.cs │ ├── KeyFactoryNormalizer.cs │ └── SavedChangesEventArgs.cs └── tests ├── Directory.Build.props ├── EntityFrameworkCoreMock.Moq.Tests ├── AutoMapperRelatedTests.cs ├── DbContextMockTests.cs ├── DbSetMockTests.cs ├── EntityFrameworkCoreMock.Moq.Tests.csproj └── Models │ ├── GeneratedGuidKeyModel.cs │ ├── GeneratedKeyModel.cs │ ├── Issue20Model.cs │ ├── NoKeyModel.cs │ ├── Order.cs │ ├── PrivateSetterPropertyModel.cs │ ├── ProtectedSetterPropertyModel.cs │ └── User.cs ├── EntityFrameworkCoreMock.NSubstitute.Tests ├── AutoMapperRelatedTests.cs ├── DbContextMockTests.cs ├── DbSetMockTests.cs ├── EntityFrameworkCoreMock.NSubstitute.Tests.csproj └── Models │ ├── GeneratedGuidKeyModel.cs │ ├── GeneratedKeyModel.cs │ ├── Issue20Model.cs │ ├── NoKeyModel.cs │ ├── Order.cs │ ├── PrivateSetterPropertyModel.cs │ └── User.cs └── EntityFrameworkCoreMock.Shared.Tests ├── EntityFrameworkCoreMock.Shared.Tests.csproj ├── KeyContextTests.cs ├── KeyFactoryBuilders ├── AttributeBasedKeyFactoryBuilderTests.cs └── ConventionBasedKeyFactoryBuilderTests.cs └── Models ├── UserWithAdditionalKeyAttribute.cs ├── UserWithIdProperty.cs ├── UserWithKeyAttribute.cs ├── UserWithKeyByConvention.cs ├── UserWithMultipleKeysByConvention.cs ├── UserWithoutKeyAttribute.cs └── UserWithoutKeyByConvention.cs /.github/FUNDING.yml: -------------------------------------------------------------------------------- 1 | github: huysentruitw 2 | -------------------------------------------------------------------------------- /.github/workflows/build-test-publish.yml: -------------------------------------------------------------------------------- 1 | name: Build, Test, Publish 2 | 3 | on: 4 | push: 5 | branches: 6 | - develop 7 | - master 8 | pull_request: 9 | branches: 10 | - develop 11 | 12 | jobs: 13 | build: 14 | runs-on: windows-latest 15 | 16 | steps: 17 | - uses: actions/checkout@v2 18 | - name: Fetch all history for all tags and branches 19 | run: git fetch --prune --unshallow 20 | - name: Install GitVersion 21 | uses: gittools/actions/gitversion/setup@v0.9.9 22 | with: 23 | versionSpec: '5.x' 24 | - name: Use GitVersion 25 | id: gitversion # step id used as reference for output values 26 | uses: gittools/actions/gitversion/execute@v0.9.9 27 | - name: Setup .NET 5 28 | uses: actions/setup-dotnet@v1 29 | with: 30 | dotnet-version: 5.0.201 31 | - name: Install dependencies 32 | run: dotnet restore 33 | - name: Build 34 | run: dotnet build --configuration Release --no-restore /p:Version=${{ steps.gitversion.outputs.nuGetVersionV2 }} 35 | - name: Test 36 | run: dotnet test --configuration Release --no-restore --no-build --verbosity normal 37 | - name: Publish 38 | if: github.ref == 'refs/heads/master' 39 | shell: pwsh 40 | run: | 41 | Get-ChildItem ".\src" -Filter "*.nupkg" -R | ForEach-Object { 42 | Write-Host "Pushing $($_.Name)" 43 | dotnet nuget push $_ --source https://api.nuget.org/v3/index.json --api-key ${{secrets.NUGET_API_KEY}} 44 | if ($lastexitcode -ne 0) { 45 | throw ("Exec: " + $errorMessage) 46 | } 47 | } 48 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | ## Ignore Visual Studio temporary files, build results, and 2 | ## files generated by popular Visual Studio add-ons. 3 | ## 4 | ## Get latest from https://github.com/github/gitignore/blob/master/VisualStudio.gitignore 5 | 6 | # User-specific files 7 | *.suo 8 | *.user 9 | *.userosscache 10 | *.sln.docstates 11 | 12 | # User-specific files (MonoDevelop/Xamarin Studio) 13 | *.userprefs 14 | 15 | # Build results 16 | [Dd]ebug/ 17 | [Dd]ebugPublic/ 18 | [Rr]elease/ 19 | [Rr]eleases/ 20 | x64/ 21 | x86/ 22 | bld/ 23 | [Bb]in/ 24 | [Oo]bj/ 25 | [Ll]og/ 26 | 27 | # Visual Studio 2015 cache/options directory 28 | .vs/ 29 | # Uncomment if you have tasks that create the project's static files in wwwroot 30 | #wwwroot/ 31 | 32 | # MSTest test Results 33 | [Tt]est[Rr]esult*/ 34 | [Bb]uild[Ll]og.* 35 | 36 | # NUNIT 37 | *.VisualState.xml 38 | TestResult.xml 39 | 40 | # Build Results of an ATL Project 41 | [Dd]ebugPS/ 42 | [Rr]eleasePS/ 43 | dlldata.c 44 | 45 | # .NET Core 46 | project.lock.json 47 | project.fragment.lock.json 48 | artifacts/ 49 | **/Properties/launchSettings.json 50 | 51 | *_i.c 52 | *_p.c 53 | *_i.h 54 | *.ilk 55 | *.meta 56 | *.obj 57 | *.pch 58 | *.pdb 59 | *.pgc 60 | *.pgd 61 | *.rsp 62 | *.sbr 63 | *.tlb 64 | *.tli 65 | *.tlh 66 | *.tmp 67 | *.tmp_proj 68 | *.log 69 | *.vspscc 70 | *.vssscc 71 | .builds 72 | *.pidb 73 | *.svclog 74 | *.scc 75 | 76 | # Chutzpah Test files 77 | _Chutzpah* 78 | 79 | # Visual C++ cache files 80 | ipch/ 81 | *.aps 82 | *.ncb 83 | *.opendb 84 | *.opensdf 85 | *.sdf 86 | *.cachefile 87 | *.VC.db 88 | *.VC.VC.opendb 89 | 90 | # Visual Studio profiler 91 | *.psess 92 | *.vsp 93 | *.vspx 94 | *.sap 95 | 96 | # TFS 2012 Local Workspace 97 | $tf/ 98 | 99 | # Guidance Automation Toolkit 100 | *.gpState 101 | 102 | # ReSharper is a .NET coding add-in 103 | _ReSharper*/ 104 | *.[Rr]e[Ss]harper 105 | *.DotSettings.user 106 | 107 | # JustCode is a .NET coding add-in 108 | .JustCode 109 | 110 | # TeamCity is a build add-in 111 | _TeamCity* 112 | 113 | # DotCover is a Code Coverage Tool 114 | *.dotCover 115 | 116 | # Visual Studio code coverage results 117 | *.coverage 118 | *.coveragexml 119 | 120 | # NCrunch 121 | _NCrunch_* 122 | .*crunch*.local.xml 123 | nCrunchTemp_* 124 | 125 | # MightyMoose 126 | *.mm.* 127 | AutoTest.Net/ 128 | 129 | # Web workbench (sass) 130 | .sass-cache/ 131 | 132 | # Installshield output folder 133 | [Ee]xpress/ 134 | 135 | # DocProject is a documentation generator add-in 136 | DocProject/buildhelp/ 137 | DocProject/Help/*.HxT 138 | DocProject/Help/*.HxC 139 | DocProject/Help/*.hhc 140 | DocProject/Help/*.hhk 141 | DocProject/Help/*.hhp 142 | DocProject/Help/Html2 143 | DocProject/Help/html 144 | 145 | # Click-Once directory 146 | publish/ 147 | 148 | # Publish Web Output 149 | *.[Pp]ublish.xml 150 | *.azurePubxml 151 | # TODO: Comment the next line if you want to checkin your web deploy settings 152 | # but database connection strings (with potential passwords) will be unencrypted 153 | *.pubxml 154 | *.publishproj 155 | 156 | # Microsoft Azure Web App publish settings. Comment the next line if you want to 157 | # checkin your Azure Web App publish settings, but sensitive information contained 158 | # in these scripts will be unencrypted 159 | PublishScripts/ 160 | 161 | # NuGet Packages 162 | *.nupkg 163 | # The packages folder can be ignored because of Package Restore 164 | **/packages/* 165 | # except build/, which is used as an MSBuild target. 166 | !**/packages/build/ 167 | # Uncomment if necessary however generally it will be regenerated when needed 168 | #!**/packages/repositories.config 169 | # NuGet v3's project.json files produces more ignorable files 170 | *.nuget.props 171 | *.nuget.targets 172 | 173 | # Microsoft Azure Build Output 174 | csx/ 175 | *.build.csdef 176 | 177 | # Microsoft Azure Emulator 178 | ecf/ 179 | rcf/ 180 | 181 | # Windows Store app package directories and files 182 | AppPackages/ 183 | BundleArtifacts/ 184 | Package.StoreAssociation.xml 185 | _pkginfo.txt 186 | 187 | # Visual Studio cache files 188 | # files ending in .cache can be ignored 189 | *.[Cc]ache 190 | # but keep track of directories ending in .cache 191 | !*.[Cc]ache/ 192 | 193 | # Others 194 | ClientBin/ 195 | ~$* 196 | *~ 197 | *.dbmdl 198 | *.dbproj.schemaview 199 | *.jfm 200 | *.pfx 201 | *.publishsettings 202 | orleans.codegen.cs 203 | 204 | # Since there are multiple workflows, uncomment next line to ignore bower_components 205 | # (https://github.com/github/gitignore/pull/1529#issuecomment-104372622) 206 | #bower_components/ 207 | 208 | # RIA/Silverlight projects 209 | Generated_Code/ 210 | 211 | # Backup & report files from converting an old project file 212 | # to a newer Visual Studio version. Backup files are not needed, 213 | # because we have git ;-) 214 | _UpgradeReport_Files/ 215 | Backup*/ 216 | UpgradeLog*.XML 217 | UpgradeLog*.htm 218 | 219 | # SQL Server files 220 | *.mdf 221 | *.ldf 222 | *.ndf 223 | 224 | # Business Intelligence projects 225 | *.rdl.data 226 | *.bim.layout 227 | *.bim_*.settings 228 | 229 | # Microsoft Fakes 230 | FakesAssemblies/ 231 | 232 | # GhostDoc plugin setting file 233 | *.GhostDoc.xml 234 | 235 | # Node.js Tools for Visual Studio 236 | .ntvs_analysis.dat 237 | node_modules/ 238 | 239 | # Typescript v1 declaration files 240 | typings/ 241 | 242 | # Visual Studio 6 build log 243 | *.plg 244 | 245 | # Visual Studio 6 workspace options file 246 | *.opt 247 | 248 | # Visual Studio 6 auto-generated workspace file (contains which files were open etc.) 249 | *.vbw 250 | 251 | # Visual Studio LightSwitch build output 252 | **/*.HTMLClient/GeneratedArtifacts 253 | **/*.DesktopClient/GeneratedArtifacts 254 | **/*.DesktopClient/ModelManifest.xml 255 | **/*.Server/GeneratedArtifacts 256 | **/*.Server/ModelManifest.xml 257 | _Pvt_Extensions 258 | 259 | # Paket dependency manager 260 | .paket/paket.exe 261 | paket-files/ 262 | 263 | # FAKE - F# Make 264 | .fake/ 265 | 266 | # JetBrains Rider 267 | .idea/ 268 | *.sln.iml 269 | 270 | # CodeRush 271 | .cr/ 272 | 273 | # Python Tools for Visual Studio (PTVS) 274 | __pycache__/ 275 | *.pyc 276 | 277 | # Cake - Uncomment if you are using it 278 | # tools/** 279 | # !tools/packages.config 280 | 281 | # Telerik's JustMock configuration file 282 | *.jmconfig 283 | 284 | # BizTalk build output 285 | *.btp.cs 286 | *.btm.cs 287 | *.odx.cs 288 | *.xsd.cs 289 | -------------------------------------------------------------------------------- /EntityFrameworkCoreMock.sln: -------------------------------------------------------------------------------- 1 |  2 | Microsoft Visual Studio Solution File, Format Version 12.00 3 | # Visual Studio 15 4 | VisualStudioVersion = 15.0.27004.2008 5 | MinimumVisualStudioVersion = 10.0.40219.1 6 | Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "EntityFrameworkCoreMock.Moq", "src\EntityFrameworkCoreMock.Moq\EntityFrameworkCoreMock.Moq.csproj", "{84B1E11A-C0A1-42F5-9F7A-0C55ED2C7D9C}" 7 | EndProject 8 | Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "EntityFrameworkCoreMock.Moq.Tests", "tests\EntityFrameworkCoreMock.Moq.Tests\EntityFrameworkCoreMock.Moq.Tests.csproj", "{28EB943C-8D7B-431C-9E44-E849043FF0D5}" 9 | EndProject 10 | Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Solution Items", "Solution Items", "{91C5E8E2-DEB7-4F2E-BBAE-2962B44F7C31}" 11 | ProjectSection(SolutionItems) = preProject 12 | LICENSE = LICENSE 13 | README.md = README.md 14 | EndProjectSection 15 | EndProject 16 | Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Moq", "Moq", "{BCEBE803-A099-48BD-AF91-FFD4FA2113FF}" 17 | EndProject 18 | Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "@Shared", "@Shared", "{E5531D22-3250-4A95-8157-D292B41CD0EE}" 19 | EndProject 20 | Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "EntityFrameworkCoreMock.Shared", "src\EntityFrameworkCoreMock.Shared\EntityFrameworkCoreMock.Shared.csproj", "{29D0B720-5189-4A96-92E0-C69AC791C0A0}" 21 | EndProject 22 | Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "EntityFrameworkCoreMock.Shared.Tests", "tests\EntityFrameworkCoreMock.Shared.Tests\EntityFrameworkCoreMock.Shared.Tests.csproj", "{9FF1D62C-2103-41BA-98BC-FDB3C13004C8}" 23 | EndProject 24 | Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "NSubstitute", "NSubstitute", "{6320D96B-E5E7-4183-964E-3A9CC7BAD043}" 25 | EndProject 26 | Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "EntityFrameworkCoreMock.NSubstitute.Tests", "tests\EntityFrameworkCoreMock.NSubstitute.Tests\EntityFrameworkCoreMock.NSubstitute.Tests.csproj", "{8E8FB4F1-578A-4DC2-B113-97B87C0E3501}" 27 | EndProject 28 | Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "EntityFrameworkCoreMock.NSubstitute", "src\EntityFrameworkCoreMock.NSubstitute\EntityFrameworkCoreMock.NSubstitute.csproj", "{2C669CD3-5428-48EE-A809-53E5B7E4E5A6}" 29 | EndProject 30 | Global 31 | GlobalSection(SolutionConfigurationPlatforms) = preSolution 32 | Debug|Any CPU = Debug|Any CPU 33 | Release|Any CPU = Release|Any CPU 34 | EndGlobalSection 35 | GlobalSection(ProjectConfigurationPlatforms) = postSolution 36 | {84B1E11A-C0A1-42F5-9F7A-0C55ED2C7D9C}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 37 | {84B1E11A-C0A1-42F5-9F7A-0C55ED2C7D9C}.Debug|Any CPU.Build.0 = Debug|Any CPU 38 | {84B1E11A-C0A1-42F5-9F7A-0C55ED2C7D9C}.Release|Any CPU.ActiveCfg = Release|Any CPU 39 | {84B1E11A-C0A1-42F5-9F7A-0C55ED2C7D9C}.Release|Any CPU.Build.0 = Release|Any CPU 40 | {28EB943C-8D7B-431C-9E44-E849043FF0D5}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 41 | {28EB943C-8D7B-431C-9E44-E849043FF0D5}.Debug|Any CPU.Build.0 = Debug|Any CPU 42 | {28EB943C-8D7B-431C-9E44-E849043FF0D5}.Release|Any CPU.ActiveCfg = Release|Any CPU 43 | {28EB943C-8D7B-431C-9E44-E849043FF0D5}.Release|Any CPU.Build.0 = Release|Any CPU 44 | {29D0B720-5189-4A96-92E0-C69AC791C0A0}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 45 | {29D0B720-5189-4A96-92E0-C69AC791C0A0}.Debug|Any CPU.Build.0 = Debug|Any CPU 46 | {29D0B720-5189-4A96-92E0-C69AC791C0A0}.Release|Any CPU.ActiveCfg = Release|Any CPU 47 | {29D0B720-5189-4A96-92E0-C69AC791C0A0}.Release|Any CPU.Build.0 = Release|Any CPU 48 | {9FF1D62C-2103-41BA-98BC-FDB3C13004C8}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 49 | {9FF1D62C-2103-41BA-98BC-FDB3C13004C8}.Debug|Any CPU.Build.0 = Debug|Any CPU 50 | {9FF1D62C-2103-41BA-98BC-FDB3C13004C8}.Release|Any CPU.ActiveCfg = Release|Any CPU 51 | {9FF1D62C-2103-41BA-98BC-FDB3C13004C8}.Release|Any CPU.Build.0 = Release|Any CPU 52 | {8E8FB4F1-578A-4DC2-B113-97B87C0E3501}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 53 | {8E8FB4F1-578A-4DC2-B113-97B87C0E3501}.Debug|Any CPU.Build.0 = Debug|Any CPU 54 | {8E8FB4F1-578A-4DC2-B113-97B87C0E3501}.Release|Any CPU.ActiveCfg = Release|Any CPU 55 | {8E8FB4F1-578A-4DC2-B113-97B87C0E3501}.Release|Any CPU.Build.0 = Release|Any CPU 56 | {2C669CD3-5428-48EE-A809-53E5B7E4E5A6}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 57 | {2C669CD3-5428-48EE-A809-53E5B7E4E5A6}.Debug|Any CPU.Build.0 = Debug|Any CPU 58 | {2C669CD3-5428-48EE-A809-53E5B7E4E5A6}.Release|Any CPU.ActiveCfg = Release|Any CPU 59 | {2C669CD3-5428-48EE-A809-53E5B7E4E5A6}.Release|Any CPU.Build.0 = Release|Any CPU 60 | EndGlobalSection 61 | GlobalSection(SolutionProperties) = preSolution 62 | HideSolutionNode = FALSE 63 | EndGlobalSection 64 | GlobalSection(NestedProjects) = preSolution 65 | {84B1E11A-C0A1-42F5-9F7A-0C55ED2C7D9C} = {BCEBE803-A099-48BD-AF91-FFD4FA2113FF} 66 | {28EB943C-8D7B-431C-9E44-E849043FF0D5} = {BCEBE803-A099-48BD-AF91-FFD4FA2113FF} 67 | {29D0B720-5189-4A96-92E0-C69AC791C0A0} = {E5531D22-3250-4A95-8157-D292B41CD0EE} 68 | {9FF1D62C-2103-41BA-98BC-FDB3C13004C8} = {E5531D22-3250-4A95-8157-D292B41CD0EE} 69 | {8E8FB4F1-578A-4DC2-B113-97B87C0E3501} = {6320D96B-E5E7-4183-964E-3A9CC7BAD043} 70 | {2C669CD3-5428-48EE-A809-53E5B7E4E5A6} = {6320D96B-E5E7-4183-964E-3A9CC7BAD043} 71 | EndGlobalSection 72 | GlobalSection(ExtensibilityGlobals) = postSolution 73 | SolutionGuid = {FB97BBBC-38CD-45AD-B426-9B8BE64C78AC} 74 | EndGlobalSection 75 | EndGlobal 76 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT license 2 | 3 | Copyright (c) 2017-2021 Wouter Huysentruit 4 | 5 | Permission is hereby granted, free of charge, to any person 6 | obtaining a copy of this software and associated documentation 7 | files (the "Software"), to deal in the Software without 8 | restriction, including without limitation the rights to use, 9 | copy, modify, merge, publish, distribute, sublicense, and/or sell 10 | copies of the Software, and to permit persons to whom the 11 | Software is furnished to do so, subject to the following 12 | conditions: 13 | 14 | The above copyright notice and this permission notice shall be 15 | included in all copies or substantial portions of the Software. 16 | 17 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, 18 | EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES 19 | OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND 20 | NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT 21 | HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, 22 | WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING 23 | FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR 24 | OTHER DEALINGS IN THE SOFTWARE. 25 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # EntityFrameworkCoreMock 2 | 3 | ![Build status](https://github.com/cup-of-tea-dot-be/entity-framework-core-mock/actions/workflows/build-test-publish.yml/badge.svg?branch=master) 4 | 5 | Easy Mock wrapper for mocking EntityFrameworkCore 5 (EFCore5) DbContext and DbSet in your unit-tests. Integrates with Moq or NSubstitute. 6 | 7 | 😢 Are you still stuck on EF Core 3.1? No worries, just visit [this repository](https://github.com/huysentruitw/entity-framework-core3-mock). 8 | 9 | 😮 Wait, did you say EF6? You really should get worried! Anyway, visit [this repository](https://github.com/huysentruitw/entity-framework-mock). 10 | 11 | ## Get it on NuGet 12 | 13 | ### Moq integration 14 | 15 | PM> Install-Package EntityFrameworkCoreMock.Moq 16 | 17 | ### NSubstitute integration 18 | 19 | PM> Install-Package EntityFrameworkCoreMock.NSubstitute 20 | 21 | ## Supports 22 | 23 | * In-memory storage of test data 24 | * Querying of in-memory test data (synchronous or asynchronous) 25 | * Tracking of updates, inserts and deletes of in-memory test data 26 | * Emulation of `SaveChanges` and `SaveChangesAsync` (only saves tracked changes to the mocked in-memory DbSet when one of these methods are called) 27 | * Auto-increment identity columns, annotated by the `[Key, DatabaseGenerated(DatabaseGeneratedOption.Identity)]` attribute 28 | * Primary key on multiple columns, annotated by the `[Key, Column(Order = X)]` attributes 29 | 30 | ## TODO 31 | 32 | * Throwing a `DbUpdateException` when inserting 2 or more entities with the same primary key while calling `SaveChanges` / `SaveChangesAsync` (emulating EF behavior) 33 | * Throwing a `DbUpdateConcurrencyException` when removing a model that no longer exists (emulating EF behavior) 34 | 35 | For the Moq version, you can use all known [Moq](https://github.com/Moq/moq4/wiki/Quickstart) features, since both `DbSetMock` and `DbContextMock` inherit from `Mock` and `Mock` respectively. 36 | 37 | ## Example usage 38 | ```C# 39 | public class User 40 | { 41 | [Key, Column(Order = 0)] 42 | public Guid Id { get; set; } 43 | 44 | public string FullName { get; set; } 45 | } 46 | 47 | public class TestDbContext : DbContext 48 | { 49 | public TestDbContext(DbContextOptions options) 50 | : base(options) 51 | { 52 | } 53 | 54 | public virtual DbSet Users { get; set; } 55 | } 56 | 57 | public class MyTests 58 | { 59 | [Fact] 60 | public void DbSetTest() 61 | { 62 | var initialEntities = new[] 63 | { 64 | new User { Id = Guid.NewGuid(), FullName = "Eric Cartoon" }, 65 | new User { Id = Guid.NewGuid(), FullName = "Billy Jewel" }, 66 | }; 67 | 68 | var dbContextMock = new DbContextMock(DummyOptions); 69 | var usersDbSetMock = dbContextMock.CreateDbSetMock(x => x.Users, initialEntities); 70 | 71 | // Pass dbContextMock.Object to the class/method you want to test 72 | 73 | // Query dbContextMock.Object.Users to see if certain users were added or removed 74 | // or use Mock Verify functionality to verify if certain methods were called: usersDbSetMock.Verify(x => x.Add(...), Times.Once); 75 | } 76 | } 77 | 78 | public DbContextOptions DummyOptions { get; } = new DbContextOptionsBuilder().Options; 79 | ``` 80 | -------------------------------------------------------------------------------- /Signing.snk: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/huysentruitw/entity-framework-core-mock/b27d2278fa53c95c2a6723af49b80df240eda33a/Signing.snk -------------------------------------------------------------------------------- /src/Directory.Build.props: -------------------------------------------------------------------------------- 1 | 2 | 3 | netstandard2.1;net5.0 4 | EntityFrameworkCoreMock 5 | 1.0.0.0 6 | Wouter Huysentruit 7 | Cup of Tea 8 | MIT 9 | https://github.com/cup-of-tea-dot-be/entity-framework-core-mock 10 | false 11 | Copyright 2017-2021 Cup of Tea 12 | true 13 | true 14 | false 15 | ../../Signing.snk 16 | 17 | 18 | -------------------------------------------------------------------------------- /src/EntityFrameworkCoreMock.Moq/DbContextMock.cs: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2017-2021 Wouter Huysentruit 3 | * 4 | * See LICENSE file. 5 | */ 6 | 7 | using System; 8 | using System.Collections.Generic; 9 | using System.Linq; 10 | using System.Linq.Expressions; 11 | using System.Threading; 12 | using Microsoft.EntityFrameworkCore; 13 | using Microsoft.EntityFrameworkCore.Infrastructure; 14 | using Microsoft.EntityFrameworkCore.Storage; 15 | using Moq; 16 | 17 | namespace EntityFrameworkCoreMock 18 | { 19 | public class DbContextMock : Mock 20 | where TDbContext : DbContext 21 | { 22 | private readonly IKeyFactoryBuilder _keyFactoryBuilder; 23 | private readonly Dictionary _dbSetCache = new Dictionary(); 24 | 25 | public DbContextMock(params object[] args) 26 | : this(new CompositeKeyFactoryBuilder(), args) 27 | { 28 | } 29 | 30 | private DbContextMock(IKeyFactoryBuilder keyFactoryBuilder, params object[] args) 31 | : base(args) 32 | { 33 | _keyFactoryBuilder = keyFactoryBuilder ?? throw new ArgumentNullException(nameof(keyFactoryBuilder)); 34 | Reset(); 35 | } 36 | 37 | public DbSetMock CreateDbSetMock(Expression>> dbSetSelector, IEnumerable initialEntities = null) 38 | where TEntity : class 39 | => CreateDbSetMock(dbSetSelector, _keyFactoryBuilder.BuildKeyFactory(), initialEntities); 40 | 41 | public DbSetMock CreateDbSetMock(Expression>> dbSetSelector, Func entityKeyFactory, IEnumerable initialEntities = null) 42 | where TEntity : class 43 | { 44 | if (dbSetSelector == null) throw new ArgumentNullException(nameof(dbSetSelector)); 45 | if (entityKeyFactory == null) throw new ArgumentNullException(nameof(entityKeyFactory)); 46 | 47 | var entityType = typeof(TEntity); 48 | if (_dbSetCache.ContainsKey(entityType)) throw new ArgumentException($"DbSetMock for entity {entityType.Name} already created", nameof(dbSetSelector)); 49 | var mock = new DbSetMock(initialEntities, entityKeyFactory); 50 | Setup(dbSetSelector).Returns(() => mock.Object); 51 | Setup(x => x.Set()).Returns(() => mock.Object); 52 | Setup(x => x.Add(It.IsAny())).Returns(entity => mock.Object.Add(entity)); 53 | Setup(x => x.AddAsync(It.IsAny(), It.IsAny())).Returns((entity, token) => mock.Object.AddAsync(entity, token)); 54 | Setup(x => x.Update(It.IsAny())).Returns(entity => mock.Object.Update(entity)); 55 | Setup(x => x.Remove(It.IsAny())).Returns(entity => mock.Object.Remove(entity)); 56 | _dbSetCache.Add(entityType, mock); 57 | return mock; 58 | } 59 | 60 | public void Reset() 61 | { 62 | MockExtensions.Reset(this); 63 | _dbSetCache.Clear(); 64 | Setup(x => x.SaveChanges()).Returns(SaveChanges); 65 | Setup(x => x.SaveChangesAsync(It.IsAny(), It.IsAny())).ReturnsAsync(SaveChanges); 66 | Setup(x => x.SaveChangesAsync(It.IsAny())).ReturnsAsync(SaveChanges); 67 | 68 | var lazyMockDbFacade = new Lazy>(() => 69 | { 70 | var mockDbFacade = new Mock(Object); 71 | var mockTransaction = new Mock(); 72 | mockDbFacade.Setup(x => x.BeginTransaction()).Returns(mockTransaction.Object); 73 | mockDbFacade.Setup(x => x.BeginTransactionAsync(It.IsAny())) 74 | .ReturnsAsync(mockTransaction.Object); 75 | return mockDbFacade; 76 | }); 77 | 78 | Setup(x => x.Database).Returns(() => lazyMockDbFacade.Value.Object); 79 | } 80 | 81 | // Facilitates unit-testing 82 | internal void RegisterDbSetMock(Expression>> dbSetSelector, IDbSetMock dbSet) 83 | where TEntity : class 84 | { 85 | var entityType = typeof(TEntity); 86 | _dbSetCache.Add(entityType, dbSet); 87 | } 88 | 89 | private int SaveChanges() => _dbSetCache.Values.Aggregate(0, (seed, dbSet) => seed + dbSet.SaveChanges()); 90 | } 91 | } 92 | -------------------------------------------------------------------------------- /src/EntityFrameworkCoreMock.Moq/DbSetMock.cs: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2017-2021 Wouter Huysentruit 3 | * 4 | * See LICENSE file. 5 | */ 6 | 7 | using System; 8 | using System.Collections; 9 | using System.Collections.Generic; 10 | using System.Linq; 11 | using System.Threading; 12 | using System.Threading.Tasks; 13 | using Microsoft.EntityFrameworkCore; 14 | using Microsoft.EntityFrameworkCore.ChangeTracking; 15 | using Moq; 16 | 17 | namespace EntityFrameworkCoreMock 18 | { 19 | public class DbSetMock : Mock>, IDbSetMock 20 | where TEntity : class 21 | { 22 | private readonly DbSetBackingStore _store; 23 | 24 | public DbSetMock(IEnumerable initialEntities, Func keyFactory, bool asyncQuerySupport = true) 25 | { 26 | _store = new DbSetBackingStore(initialEntities, keyFactory); 27 | 28 | var data = _store.GetDataAsQueryable(); 29 | As>().Setup(x => x.Provider).Returns(asyncQuerySupport ? new DbAsyncQueryProvider(data.Provider) : data.Provider); 30 | As>().Setup(x => x.Expression).Returns(data.Expression); 31 | As>().Setup(x => x.ElementType).Returns(data.ElementType); 32 | As>().Setup(x => x.GetEnumerator()).Returns(() => data.GetEnumerator()); 33 | As().Setup(x => x.GetEnumerator()).Returns(() => data.GetEnumerator()); 34 | 35 | if (asyncQuerySupport) 36 | { 37 | As>().Setup(x => x.GetAsyncEnumerator(It.IsAny())).Returns(() => new DbAsyncEnumerator(data.GetEnumerator())); 38 | } 39 | 40 | Setup(x => x.Add(It.IsAny())).Callback(_store.Add); 41 | Setup(x => x.AddRange(It.IsAny())).Callback(_store.Add); 42 | Setup(x => x.AddRange(It.IsAny>())).Callback>(_store.Add); 43 | Setup(x => x.Update(It.IsAny())).Callback(_store.Update); 44 | Setup(x => x.UpdateRange(It.IsAny())).Callback(_store.Update); 45 | Setup(x => x.UpdateRange(It.IsAny>())).Callback>(_store.Update); 46 | Setup(x => x.Remove(It.IsAny())).Callback(_store.Remove); 47 | Setup(x => x.RemoveRange(It.IsAny())).Callback(_store.Remove); 48 | Setup(x => x.RemoveRange(It.IsAny>())).Callback>(_store.Remove); 49 | 50 | Setup(x => x.AddAsync(It.IsAny(), It.IsAny())).Callback((x, _) => _store.Add(x)).ReturnsAsync(default(EntityEntry)); 51 | Setup(x => x.AddRangeAsync(It.IsAny())).Callback(_store.Add).Returns(Task.CompletedTask); 52 | Setup(x => x.AddRangeAsync(It.IsAny>(), It.IsAny())).Callback, CancellationToken>((x, _) => _store.Add(x)).Returns(Task.CompletedTask); 53 | 54 | Setup(x => x.Find(It.IsAny())).Returns(_store.Find); 55 | Setup(x => x.FindAsync(It.IsAny())).Returns(x => new ValueTask(_store.Find(x))); 56 | Setup(x => x.FindAsync(It.IsAny(), It.IsAny())).Returns((x, _) => new ValueTask(_store.Find(x))); 57 | 58 | _store.UpdateSnapshot(); 59 | } 60 | 61 | public event EventHandler> SavedChanges; 62 | 63 | int IDbSetMock.SaveChanges() 64 | { 65 | var changes = _store.ApplyChanges(); 66 | SavedChanges?.Invoke(this, new SavedChangesEventArgs { UpdatedEntities = _store.GetUpdatedEntities() }); 67 | _store.UpdateSnapshot(); 68 | return changes; 69 | } 70 | } 71 | } 72 | -------------------------------------------------------------------------------- /src/EntityFrameworkCoreMock.Moq/EntityFrameworkCoreMock.Moq.csproj: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | EntityFrameworkCoreMock.Moq 5 | Easy Mock wrapper for mocking EntityFrameworkCore 5 (EFCore5) DbContext and DbSet using Moq 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | -------------------------------------------------------------------------------- /src/EntityFrameworkCoreMock.Moq/_Visibility.cs: -------------------------------------------------------------------------------- 1 | using System.Runtime.CompilerServices; 2 | 3 | [assembly:InternalsVisibleTo("EntityFrameworkCoreMock.Moq.Tests, PublicKey=00240000048000009400000006020000002400005253413100040000010001007969fa10a1fd2a36059acd8212eeb5b7edd1304089111d038dee105be136cc0cb48fc90a7d3a6b71c25f715b363034e00d4f00dd8a4385ab510eef26d5a8fddc6f4d60b64689ebbcea17437d74655fe8316e0387e383657b931160c7f9524a1cdc1f2b1767af97975c5ce87c3eabf1e076dd757bf39bd43aaebc8d90d183f4bf")] 4 | -------------------------------------------------------------------------------- /src/EntityFrameworkCoreMock.NSubstitute/DbContextMock.cs: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2017-2021 Wouter Huysentruit 3 | * 4 | * See LICENSE file. 5 | */ 6 | 7 | using System; 8 | using System.Collections.Generic; 9 | using System.Linq; 10 | using System.Linq.Expressions; 11 | using System.Threading; 12 | using Microsoft.EntityFrameworkCore; 13 | using Microsoft.EntityFrameworkCore.Infrastructure; 14 | using NSubstitute; 15 | 16 | namespace EntityFrameworkCoreMock.NSubstitute 17 | { 18 | public class DbContextMock where TDbContext : DbContext 19 | { 20 | private readonly IKeyFactoryBuilder _keyFactoryBuilder; 21 | private readonly Dictionary _dbSetCache = new Dictionary(); 22 | 23 | public TDbContext Object { get; set; } 24 | 25 | public DbContextMock(params object[] args) 26 | : this(new CompositeKeyFactoryBuilder(), args) 27 | { 28 | } 29 | 30 | private DbContextMock(IKeyFactoryBuilder keyFactoryBuilder, params object[] args) 31 | { 32 | Object = Substitute.For(args); 33 | Object.Database.Returns(Substitute.For(Object)); 34 | _keyFactoryBuilder = keyFactoryBuilder ?? throw new ArgumentNullException(nameof(keyFactoryBuilder)); 35 | Reset(); 36 | } 37 | 38 | public DbSetMock CreateDbSetMock(Expression>> dbSetSelector, IEnumerable initialEntities = null) 39 | where TEntity : class 40 | => CreateDbSetMock(dbSetSelector, _keyFactoryBuilder.BuildKeyFactory(), initialEntities); 41 | 42 | public DbSetMock CreateDbSetMock( 43 | Expression>> dbSetSelector, 44 | Func entityKeyFactory, 45 | IEnumerable initialEntities = null) 46 | where TEntity : class 47 | { 48 | if (dbSetSelector == null) throw new ArgumentNullException(nameof(dbSetSelector)); 49 | if (entityKeyFactory == null) throw new ArgumentNullException(nameof(entityKeyFactory)); 50 | 51 | var entityType = typeof(TEntity); 52 | if (_dbSetCache.ContainsKey(entityType)) throw new ArgumentException($"DbSetMock for entity {entityType.Name} already created", nameof(dbSetSelector)); 53 | var mock = new DbSetMock(initialEntities, entityKeyFactory); 54 | Object.Set().Returns(mock.Object); 55 | Object.Add(Arg.Any()).Returns(callInfo => mock.Object.Add(callInfo.Arg())); 56 | Object.AddAsync(Arg.Any()).Returns(callInfo => mock.Object.AddAsync(callInfo.Arg())); 57 | Object.Update(Arg.Any()).Returns(callInfo => mock.Object.Update(callInfo.Arg())); 58 | Object.Remove(Arg.Any()).Returns(callInfo => mock.Object.Remove(callInfo.Arg())); 59 | 60 | dbSetSelector.Compile()(Object).Returns(mock.Object); 61 | 62 | _dbSetCache.Add(entityType, mock); 63 | return mock; 64 | } 65 | 66 | public void Reset() 67 | { 68 | _dbSetCache.Clear(); 69 | Object.ClearReceivedCalls(); 70 | Object.SaveChanges().Returns(_ => SaveChanges()); 71 | Object.SaveChanges(Arg.Any()).Returns(_ => SaveChanges()); 72 | Object.SaveChangesAsync().Returns(_ => SaveChanges()); 73 | Object.SaveChangesAsync(Arg.Any()).Returns(_ => SaveChanges()); 74 | } 75 | 76 | // Facilitates unit-testing 77 | internal void RegisterDbSetMock(Expression>> dbSetSelector, IDbSetMock dbSet) 78 | where TEntity : class 79 | { 80 | var entityType = typeof(TEntity); 81 | _dbSetCache.Add(entityType, dbSet); 82 | } 83 | 84 | private int SaveChanges() => _dbSetCache.Values.Aggregate(0, (seed, dbSet) => seed + dbSet.SaveChanges()); 85 | } 86 | } 87 | -------------------------------------------------------------------------------- /src/EntityFrameworkCoreMock.NSubstitute/DbSetMock.cs: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2017-2021 Wouter Huysentruit 3 | * 4 | * See LICENSE file. 5 | */ 6 | 7 | using System; 8 | using System.Collections; 9 | using System.Collections.Generic; 10 | using System.Linq; 11 | using System.Threading; 12 | using System.Threading.Tasks; 13 | using Microsoft.EntityFrameworkCore; 14 | using Microsoft.EntityFrameworkCore.ChangeTracking; 15 | using NSubstitute; 16 | 17 | namespace EntityFrameworkCoreMock.NSubstitute 18 | { 19 | public class DbSetMock : IDbSetMock 20 | where TEntity : class 21 | { 22 | private readonly DbSetBackingStore _store; 23 | 24 | public DbSet Object { get; } 25 | 26 | public DbSetMock(IEnumerable initialEntities, Func keyFactory, bool asyncQuerySupport = true) 27 | { 28 | _store = new DbSetBackingStore(initialEntities, keyFactory); 29 | 30 | var data = _store.GetDataAsQueryable(); 31 | 32 | Object = Substitute.For, IQueryable, IAsyncEnumerable>(); 33 | 34 | ((IQueryable)Object).Provider.Returns(asyncQuerySupport ? new DbAsyncQueryProvider(data.Provider) : data.Provider); 35 | ((IQueryable)Object).Expression.Returns(data.Expression); 36 | ((IQueryable)Object).ElementType.Returns(data.ElementType); 37 | ((IQueryable)Object).GetEnumerator().Returns(a => data.GetEnumerator()); 38 | ((IEnumerable)Object).GetEnumerator().Returns(a => data.GetEnumerator()); 39 | 40 | if (asyncQuerySupport) 41 | { 42 | ((IAsyncEnumerable)Object).GetAsyncEnumerator(default).Returns(a => new DbAsyncEnumerator(data.GetEnumerator())); 43 | } 44 | 45 | Object.When(a => a.Add(Arg.Any())).Do(b => _store.Add(b.ArgAt(0))); 46 | Object.When(a => a.AddRange(Arg.Any())).Do(b => _store.Add(b.ArgAt(0))); 47 | Object.When(a => a.AddRange(Arg.Any>())).Do(b => _store.Add(b.ArgAt>(0))); 48 | Object.When(a => a.Update(Arg.Any())).Do(b => _store.Update(b.ArgAt(0))); 49 | Object.When(a => a.UpdateRange(Arg.Any())).Do(b => _store.Update(b.ArgAt(0))); 50 | Object.When(a => a.UpdateRange(Arg.Any>())).Do(b => _store.Update(b.ArgAt>(0))); 51 | Object.When(a => a.Remove(Arg.Any())).Do(b => _store.Remove(b.ArgAt(0))); 52 | Object.When(a => a.RemoveRange(Arg.Any())).Do(b => _store.Remove(b.ArgAt(0))); 53 | Object.When(a => a.RemoveRange(Arg.Any>())).Do(b => _store.Remove(b.ArgAt>(0))); 54 | 55 | Object.AddAsync(Arg.Any(), Arg.Any()).Returns(info => 56 | { 57 | _store.Add(info.ArgAt(0)); 58 | return default(EntityEntry); 59 | }); 60 | Object.AddRangeAsync(Arg.Any()).Returns(info => 61 | { 62 | _store.Add(info.ArgAt(0)); 63 | return Task.CompletedTask; 64 | }); 65 | Object.AddRangeAsync(Arg.Any>(), Arg.Any()).Returns(info => 66 | { 67 | _store.Add(info.ArgAt>(0)); 68 | return Task.CompletedTask; 69 | }); 70 | 71 | Object.Find(Arg.Any()).Returns(info => _store.Find(info.Args()[0] as object[])); 72 | Object.FindAsync(Arg.Any()).Returns(info => new ValueTask(_store.Find(info.Args()[0] as object[]))); 73 | Object.FindAsync(Arg.Any(), Arg.Any()).Returns(info => new ValueTask(_store.Find(info.Args()[0] as object[]))); 74 | 75 | _store.UpdateSnapshot(); 76 | } 77 | 78 | public event EventHandler> SavedChanges; 79 | 80 | int IDbSetMock.SaveChanges() 81 | { 82 | var changes = _store.ApplyChanges(); 83 | SavedChanges?.Invoke(this, new SavedChangesEventArgs { UpdatedEntities = _store.GetUpdatedEntities() }); 84 | _store.UpdateSnapshot(); 85 | return changes; 86 | } 87 | } 88 | } 89 | -------------------------------------------------------------------------------- /src/EntityFrameworkCoreMock.NSubstitute/EntityFrameworkCoreMock.NSubstitute.csproj: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | EntityFrameworkCoreMock.NSubstitute 5 | Easy Mock wrapper for mocking EntityFrameworkCore 5 (EFCore5) DbContext and DbSet using NSubstitute 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | -------------------------------------------------------------------------------- /src/EntityFrameworkCoreMock.NSubstitute/_Visibility.cs: -------------------------------------------------------------------------------- 1 | using System.Runtime.CompilerServices; 2 | 3 | [assembly:InternalsVisibleTo("EntityFrameworkCoreMock.NSubstitute.Tests, PublicKey=00240000048000009400000006020000002400005253413100040000010001007969fa10a1fd2a36059acd8212eeb5b7edd1304089111d038dee105be136cc0cb48fc90a7d3a6b71c25f715b363034e00d4f00dd8a4385ab510eef26d5a8fddc6f4d60b64689ebbcea17437d74655fe8316e0387e383657b931160c7f9524a1cdc1f2b1767af97975c5ce87c3eabf1e076dd757bf39bd43aaebc8d90d183f4bf")] 4 | -------------------------------------------------------------------------------- /src/EntityFrameworkCoreMock.Shared/CompositeKeyFactoryBuilder.cs: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2017-2021 Wouter Huysentruit 3 | * 4 | * See LICENSE file. 5 | */ 6 | 7 | using System; 8 | using System.Collections.Generic; 9 | using System.ComponentModel.DataAnnotations; 10 | 11 | namespace EntityFrameworkCoreMock 12 | { 13 | public sealed class CompositeKeyFactoryBuilder : IKeyFactoryBuilder 14 | { 15 | private readonly AttributeBasedKeyFactoryBuilder _attributeBasedKeyFactoryBuilder 16 | = new AttributeBasedKeyFactoryBuilder(); 17 | private readonly ConventionBasedKeyFactoryBuilder _conventionBasedKeyFactoryBuilder 18 | = new ConventionBasedKeyFactoryBuilder(); 19 | 20 | public Func BuildKeyFactory() 21 | { 22 | var exceptions = new List(); 23 | 24 | try 25 | { 26 | return _attributeBasedKeyFactoryBuilder.BuildKeyFactory(); 27 | } 28 | catch (Exception ex) 29 | { 30 | exceptions.Add(ex); 31 | } 32 | 33 | try 34 | { 35 | return _conventionBasedKeyFactoryBuilder.BuildKeyFactory(); 36 | } 37 | catch (Exception ex) 38 | { 39 | exceptions.Add(ex); 40 | } 41 | 42 | throw new AggregateException($"No key factory could be created for entity type {typeof(T).Name}, see inner exceptions", exceptions); 43 | } 44 | } 45 | } 46 | -------------------------------------------------------------------------------- /src/EntityFrameworkCoreMock.Shared/DbAsyncEnumerable.cs: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2017-2021 Wouter Huysentruit 3 | * 4 | * See LICENSE file. 5 | */ 6 | 7 | using System; 8 | using System.Collections; 9 | using System.Collections.Generic; 10 | using System.Linq; 11 | using System.Linq.Expressions; 12 | using System.Threading; 13 | 14 | namespace EntityFrameworkCoreMock 15 | { 16 | public class DbAsyncEnumerable : IAsyncEnumerable, IOrderedQueryable 17 | { 18 | private readonly IEnumerable _enumerable; 19 | 20 | public DbAsyncEnumerable(Expression expression) 21 | { 22 | Expression = expression; 23 | _enumerable = CompileExpression>(expression); 24 | } 25 | 26 | public DbAsyncEnumerable(IEnumerable enumerable) 27 | { 28 | Expression = enumerable.AsQueryable().Expression; 29 | _enumerable = enumerable; 30 | } 31 | 32 | IEnumerator IEnumerable.GetEnumerator() 33 | => _enumerable.GetEnumerator(); 34 | 35 | IAsyncEnumerator IAsyncEnumerable.GetAsyncEnumerator(CancellationToken cancellationToken) 36 | => new DbAsyncEnumerator(this.AsEnumerable().GetEnumerator()); 37 | 38 | IEnumerator IEnumerable.GetEnumerator() 39 | => _enumerable.GetEnumerator(); 40 | 41 | public Type ElementType => typeof(TEntity); 42 | 43 | public Expression Expression { get; } 44 | 45 | public IQueryProvider Provider => new DbAsyncQueryProvider(_enumerable.AsQueryable().Provider); 46 | 47 | private static T CompileExpression(Expression expression) 48 | => Expression.Lambda>( 49 | body: new Visitor().Visit(expression) ?? throw new InvalidOperationException("Visitor returns null"), 50 | parameters: (IEnumerable) null) 51 | .Compile()(); 52 | 53 | private class Visitor : ExpressionVisitor { } 54 | } 55 | } 56 | -------------------------------------------------------------------------------- /src/EntityFrameworkCoreMock.Shared/DbAsyncEnumerator.cs: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2017-2021 Wouter Huysentruit 3 | * 4 | * See LICENSE file. 5 | */ 6 | 7 | using System.Collections.Generic; 8 | using System.Threading.Tasks; 9 | 10 | namespace EntityFrameworkCoreMock 11 | { 12 | public class DbAsyncEnumerator : IAsyncEnumerator 13 | { 14 | private readonly IEnumerator _inner; 15 | 16 | public DbAsyncEnumerator(IEnumerator inner) 17 | { 18 | _inner = inner; 19 | } 20 | 21 | public ValueTask MoveNextAsync() 22 | => new ValueTask(_inner.MoveNext()); 23 | 24 | public ValueTask DisposeAsync() 25 | { 26 | _inner.Dispose(); 27 | return default; 28 | } 29 | 30 | public TEntity Current => _inner.Current; 31 | } 32 | } 33 | -------------------------------------------------------------------------------- /src/EntityFrameworkCoreMock.Shared/DbAsyncQueryProvider.cs: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2017-2021 Wouter Huysentruit 3 | * 4 | * See LICENSE file. 5 | */ 6 | 7 | using System; 8 | using System.Collections.Generic; 9 | using System.Linq; 10 | using System.Linq.Expressions; 11 | using System.Threading; 12 | using System.Threading.Tasks; 13 | using Microsoft.EntityFrameworkCore.Query; 14 | 15 | namespace EntityFrameworkCoreMock 16 | { 17 | public class DbAsyncQueryProvider : IAsyncQueryProvider 18 | { 19 | private readonly IQueryProvider _inner; 20 | 21 | public DbAsyncQueryProvider(IQueryProvider inner) 22 | { 23 | _inner = inner; 24 | } 25 | 26 | public IQueryable CreateQuery(Expression expression) 27 | { 28 | if (expression is MethodCallExpression m) 29 | { 30 | var resultType = m.Method.ReturnType; // it should be IQueryable 31 | var tElement = resultType.GetGenericArguments().First(); 32 | var queryType = typeof(DbAsyncEnumerable<>).MakeGenericType(tElement); 33 | return (IQueryable)Activator.CreateInstance(queryType, expression); 34 | } 35 | 36 | return new DbAsyncEnumerable(expression); 37 | } 38 | 39 | public IQueryable CreateQuery(Expression expression) 40 | { 41 | return new DbAsyncEnumerable(expression); 42 | } 43 | 44 | public object Execute(Expression expression) 45 | { 46 | return CompileExpressionItem(expression); 47 | } 48 | 49 | public TResult Execute(Expression expression) 50 | { 51 | return CompileExpressionItem(expression); 52 | } 53 | 54 | public TResult ExecuteAsync(Expression expression, CancellationToken cancellationToken) 55 | { 56 | var expectedResultType = typeof(TResult).GetGenericArguments()[0]; 57 | var executionResult = typeof(IQueryProvider) 58 | .GetMethod( 59 | name: nameof(IQueryProvider.Execute), 60 | genericParameterCount: 1, 61 | types: new[] { typeof(Expression) }) 62 | .MakeGenericMethod(expectedResultType) 63 | .Invoke(this, new[] { expression }); 64 | 65 | return (TResult)typeof(Task).GetMethod(nameof(Task.FromResult)) 66 | .MakeGenericMethod(expectedResultType) 67 | .Invoke(null, new[] { executionResult }); 68 | } 69 | 70 | private static T CompileExpressionItem(Expression expression) 71 | => Expression.Lambda>( 72 | body: new Visitor().Visit(expression) ?? throw new InvalidOperationException("Visitor returns null"), 73 | parameters: (IEnumerable) null) 74 | .Compile()(); 75 | 76 | private class Visitor : ExpressionVisitor { } 77 | } 78 | } 79 | -------------------------------------------------------------------------------- /src/EntityFrameworkCoreMock.Shared/DbSetBackingStore.cs: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2017-2021 Wouter Huysentruit 3 | * 4 | * See LICENSE file. 5 | */ 6 | 7 | using System; 8 | using System.Collections.Concurrent; 9 | using System.Collections.Generic; 10 | using System.ComponentModel.DataAnnotations.Schema; 11 | using System.Linq; 12 | using System.Linq.Expressions; 13 | using System.Reflection; 14 | using System.Threading; 15 | 16 | namespace EntityFrameworkCoreMock 17 | { 18 | public sealed class DbSetBackingStore 19 | where TEntity : class 20 | { 21 | private readonly KeyFactoryNormalizer _keyFactoryNormalizer; 22 | private readonly Dictionary _entities = new Dictionary(); 23 | private readonly Dictionary _snapshot = new Dictionary(); 24 | private List _changes = new List(); 25 | private readonly KeyContext _keyContext = new KeyContext(); 26 | 27 | public DbSetBackingStore(IEnumerable initialEntities, Func keyFactory) 28 | { 29 | _keyFactoryNormalizer = new KeyFactoryNormalizer(keyFactory ?? throw new ArgumentNullException(nameof(keyFactory))); 30 | initialEntities?.ToList().ForEach(x => _entities.Add(_keyFactoryNormalizer.GenerateKey(x, _keyContext), Clone(x))); 31 | } 32 | 33 | public IQueryable GetDataAsQueryable() => _entities.Values.AsQueryable(); 34 | 35 | /// 36 | /// Registers the addition of a new entity. 37 | /// 38 | /// The new entity. 39 | public void Add(TEntity entity) => _changes.Add(DbSetChange.Add(entity)); 40 | 41 | /// 42 | /// Registers the addition of one or more entities. 43 | /// 44 | /// The list of entities. 45 | public void Add(IEnumerable entities) => _changes.AddRange(DbSetChange.Add(entities)); 46 | 47 | /// 48 | /// Find an entity by its key. 49 | /// 50 | /// The key. 51 | /// The entity or null in case no entity with a matching key was found. 52 | public TEntity Find(object[] keyValues) 53 | { 54 | var tupleType = Type.GetType($"System.Tuple`{keyValues.Length}"); 55 | if (tupleType == null) throw new InvalidOperationException($"No tuple type found for {keyValues.Length} generic arguments"); 56 | 57 | var keyTypes = keyValues.Select(x => x.GetType()).ToArray(); 58 | var constructor = tupleType.MakeGenericType(keyTypes).GetConstructor(keyTypes); 59 | if (constructor == null) throw new InvalidOperationException("No tuple constructor found for key values"); 60 | 61 | var key = constructor.Invoke(keyValues); 62 | return _entities.TryGetValue(key, out var entity) ? entity : null; 63 | } 64 | 65 | /// 66 | /// Registers the update of an entity. 67 | /// 68 | /// 69 | public void Update(TEntity entity) => _changes.Add(DbSetChange.Update(entity)); 70 | 71 | /// 72 | /// Registers the update of one or more entities. 73 | /// 74 | /// 75 | public void Update(IEnumerable entities) => _changes.AddRange(DbSetChange.Update(entities)); 76 | 77 | /// 78 | /// Registers the removal of an entity. 79 | /// 80 | /// The removed entity. 81 | public void Remove(TEntity entity) => _changes.Add(DbSetChange.Remove(entity)); 82 | 83 | /// 84 | /// Registers the removal of one or more entities. 85 | /// 86 | /// The list of removed entities. 87 | public void Remove(IEnumerable entities) => _changes.AddRange(DbSetChange.Remove(entities)); 88 | 89 | /// 90 | /// Applies the registered changes to the collection of entities. 91 | /// 92 | /// The number of changes that got applied. 93 | public int ApplyChanges() 94 | { 95 | var changes = Interlocked.Exchange(ref _changes, new List()); 96 | foreach (var change in changes) 97 | { 98 | if (change.IsAdd) AddEntity(change.Entity); 99 | else if (change.IsUpdate) UpdateEntity(change.Entity); 100 | else if (change.IsRemove) RemoveEntity(change.Entity); 101 | } 102 | 103 | return changes.Count; 104 | } 105 | 106 | /// 107 | /// Updates the snapshot of the entities that is used to detect updated properties. 108 | /// 109 | public void UpdateSnapshot() 110 | { 111 | _snapshot.Clear(); 112 | foreach (var kvp in _entities) 113 | _snapshot.Add(kvp.Key, Clone(kvp.Value)); 114 | } 115 | 116 | /// 117 | /// Gets a list of entities that have one or more properties updated (as compared to the last snapshot). 118 | /// 119 | /// The list of updated entities. 120 | public UpdatedEntityInfo[] GetUpdatedEntities() 121 | { 122 | return _entities 123 | .Join( 124 | _snapshot, 125 | entity => entity.Key, 126 | snapshot => snapshot.Key, 127 | (entity, snapshot) => 128 | new UpdatedEntityInfo 129 | { 130 | Entity = entity.Value, 131 | UpdatedProperties = Diff(snapshot.Value, entity.Value) 132 | } 133 | ) 134 | .Where(x => x.UpdatedProperties.Any()) 135 | .ToArray(); 136 | } 137 | 138 | private void AddEntity(TEntity entity) 139 | { 140 | var key = _keyFactoryNormalizer.GenerateKey(entity, _keyContext); 141 | if (_entities.ContainsKey(key)) ThrowDbUpdateException(); 142 | _entities.Add(key, entity); 143 | } 144 | 145 | private void UpdateEntity(TEntity entity) 146 | { 147 | var key = _keyFactoryNormalizer.GenerateKey(entity, _keyContext); 148 | if (!_entities.ContainsKey(key)) ThrowDbUpdateException(); 149 | _entities[key] = entity; 150 | } 151 | 152 | private void RemoveEntity(TEntity entity) 153 | { 154 | var key = _keyFactoryNormalizer.GenerateKey(entity, _keyContext); 155 | if (!_entities.Remove(key)) ThrowDbUpdateConcurrencyException(); 156 | } 157 | 158 | private static void ThrowDbUpdateException() 159 | { 160 | // TODO implement 161 | } 162 | 163 | private static void ThrowDbUpdateConcurrencyException() 164 | { 165 | // TODO implement 166 | } 167 | 168 | private static UpdatePropertyInfo[] Diff(TEntity snapshot, TEntity current) 169 | { 170 | var properties = snapshot.GetType().GetProperties(BindingFlags.Instance | BindingFlags.Public) 171 | .Where(x => x.CanRead && x.CanWrite && x.GetCustomAttribute() == null) 172 | .Where(x => x.GetSetMethod() != null) 173 | .ToArray(); 174 | 175 | return properties 176 | .Select(x => new UpdatePropertyInfo 177 | { 178 | Name = x.Name, 179 | Original = x.GetValue(snapshot), 180 | New = x.GetValue(current) 181 | }) 182 | .Where(x => !object.Equals(x.New, x.Original)) 183 | .ToArray(); 184 | } 185 | 186 | private static TEntity Clone(TEntity original) => CloneFuncCache.GetOrAdd(original.GetType(), CreateCloneFunc)(original); 187 | private static readonly ConcurrentDictionary> CloneFuncCache = new ConcurrentDictionary>(); 188 | private static Func CreateCloneFunc(Type entityType) 189 | { 190 | var properties = entityType.GetProperties(BindingFlags.Instance | BindingFlags.Public) 191 | .Where(x => x.CanRead && x.CanWrite && x.GetCustomAttribute() == null) 192 | .Where(x => x.GetSetMethod(nonPublic: true) != null) 193 | .ToArray(); 194 | 195 | var original = Expression.Parameter(typeof(TEntity), "original"); 196 | var clone = Expression.Variable(entityType, "clone"); 197 | var newClone = Expression.New(entityType); 198 | var cloneBlock = Expression.Block( 199 | new[] { clone }, 200 | Expression.Assign(clone, newClone), 201 | Expression.Block( 202 | properties.Select(propertyInfo => 203 | { 204 | var getter = Expression.Property(Expression.Convert(original, entityType), propertyInfo); 205 | var setter = propertyInfo.GetSetMethod(nonPublic: true); 206 | return Expression.Call(clone, setter, getter); 207 | }) 208 | ), 209 | clone); 210 | 211 | return Expression.Lambda>(cloneBlock, original).Compile(); 212 | } 213 | 214 | private class DbSetChange 215 | { 216 | public bool IsAdd { get; private set; } 217 | 218 | public bool IsUpdate { get; private set; } 219 | 220 | public bool IsRemove { get; private set; } 221 | 222 | public TEntity Entity { get; private set; } 223 | 224 | public static DbSetChange Add(TEntity entity) => new DbSetChange { IsAdd = true, Entity = entity }; 225 | 226 | public static IEnumerable Add(IEnumerable entities) => entities.Select(DbSetChange.Add); 227 | 228 | public static DbSetChange Update(TEntity entity) => new DbSetChange { IsUpdate = true, Entity = entity }; 229 | 230 | public static IEnumerable Update(IEnumerable entities) => entities.Select(DbSetChange.Update); 231 | 232 | public static DbSetChange Remove(TEntity entity) => new DbSetChange { IsRemove = true, Entity = entity }; 233 | 234 | public static IEnumerable Remove(IEnumerable entities) => entities.Select(DbSetChange.Remove); 235 | } 236 | } 237 | } 238 | -------------------------------------------------------------------------------- /src/EntityFrameworkCoreMock.Shared/EntityFrameworkCoreMock.Shared.csproj: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | EntityFrameworkCoreMock.Shared 5 | Shared code for EntityFrameworkCoreMock 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | -------------------------------------------------------------------------------- /src/EntityFrameworkCoreMock.Shared/IDbQueryMock.cs: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2017-2021 Wouter Huysentruit 3 | * 4 | * See LICENSE file. 5 | */ 6 | 7 | namespace EntityFrameworkCoreMock 8 | { 9 | public interface IDbQueryMock 10 | { 11 | } 12 | } 13 | -------------------------------------------------------------------------------- /src/EntityFrameworkCoreMock.Shared/IDbSetMock.cs: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2017-2021 Wouter Huysentruit 3 | * 4 | * See LICENSE file. 5 | */ 6 | 7 | namespace EntityFrameworkCoreMock 8 | { 9 | public interface IDbSetMock 10 | { 11 | int SaveChanges(); 12 | } 13 | } 14 | -------------------------------------------------------------------------------- /src/EntityFrameworkCoreMock.Shared/IKeyFactoryBuilder.cs: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2017-2021 Wouter Huysentruit 3 | * 4 | * See LICENSE file. 5 | */ 6 | 7 | using System; 8 | 9 | namespace EntityFrameworkCoreMock 10 | { 11 | public interface IKeyFactoryBuilder 12 | { 13 | Func BuildKeyFactory(); 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /src/EntityFrameworkCoreMock.Shared/KeyContext.cs: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2017-2021 Wouter Huysentruit 3 | * 4 | * See LICENSE file. 5 | */ 6 | 7 | namespace EntityFrameworkCoreMock 8 | { 9 | public sealed class KeyContext 10 | { 11 | private long _nextIdentity = 1; 12 | 13 | public long NextIdentity => _nextIdentity++; 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /src/EntityFrameworkCoreMock.Shared/KeyFactoryBuilders/AttributeBasedKeyFactoryBuilder.cs: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2017-2021 Wouter Huysentruit 3 | * 4 | * See LICENSE file. 5 | */ 6 | 7 | using System; 8 | using System.Linq; 9 | using System.Reflection; 10 | using EntityFrameworkCoreMock.Shared.KeyFactoryBuilders; 11 | 12 | namespace EntityFrameworkCoreMock 13 | { 14 | public sealed class AttributeBasedKeyFactoryBuilder : KeyFactoryBuilderBase 15 | where TAttribute : Attribute 16 | { 17 | protected override PropertyInfo[] ResolveKeyProperties() 18 | { 19 | var entityType = typeof(T); 20 | var keyProperties = entityType.GetProperties(BindingFlags.Instance | BindingFlags.Public) 21 | .Where(x => x.GetCustomAttribute(typeof(TAttribute)) != null) 22 | .ToArray(); 23 | if (!keyProperties.Any()) throw new InvalidOperationException($"Entity type {entityType.Name} does not contain any property marked with {typeof(TAttribute).Name}"); 24 | return keyProperties; 25 | } 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /src/EntityFrameworkCoreMock.Shared/KeyFactoryBuilders/ConventionBasedKeyFactoryBuilder.cs: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2017-2021 Wouter Huysentruit 3 | * 4 | * See LICENSE file. 5 | */ 6 | 7 | using System; 8 | using System.Linq; 9 | using System.Reflection; 10 | using EntityFrameworkCoreMock.Shared.KeyFactoryBuilders; 11 | 12 | namespace EntityFrameworkCoreMock 13 | { 14 | public sealed class ConventionBasedKeyFactoryBuilder : KeyFactoryBuilderBase 15 | { 16 | protected override PropertyInfo[] ResolveKeyProperties() 17 | { 18 | var entityType = typeof(T); 19 | var keyProperties = entityType.GetProperties(BindingFlags.Instance | BindingFlags.Public) 20 | .Where(x => x.Name.Equals("Id") || x.Name.Equals($"{entityType.Name}Id")) 21 | .ToArray(); 22 | if (!keyProperties.Any()) throw new InvalidOperationException($"Entity type {entityType.Name} does not contain any property named Id or {entityType.Name}Id"); 23 | if (keyProperties.Count() > 1) throw new InvalidOperationException($"Entity type {entityType.Name} contains multiple conventional id properties"); 24 | return keyProperties; 25 | } 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /src/EntityFrameworkCoreMock.Shared/KeyFactoryBuilders/KeyFactoryBuilderBase.cs: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2017-2021 Wouter Huysentruit 3 | * 4 | * See LICENSE file. 5 | */ 6 | 7 | using System; 8 | using System.ComponentModel.DataAnnotations.Schema; 9 | using System.Linq; 10 | using System.Linq.Expressions; 11 | using System.Reflection; 12 | 13 | namespace EntityFrameworkCoreMock.Shared.KeyFactoryBuilders 14 | { 15 | public abstract class KeyFactoryBuilderBase : IKeyFactoryBuilder 16 | { 17 | public Func BuildKeyFactory() 18 | { 19 | var keyProperties = ResolveKeyProperties(); 20 | var keyFactory = BuildIdentityKeyFactory(keyProperties); 21 | keyFactory = keyFactory ?? BuildDefaultKeyFactory(keyProperties); 22 | return keyFactory; 23 | } 24 | 25 | protected abstract PropertyInfo[] ResolveKeyProperties(); 26 | 27 | private static Func BuildIdentityKeyFactory(PropertyInfo[] keyProperties) 28 | { 29 | if (keyProperties.Length != 1) return null; 30 | var keyProperty = keyProperties[0]; 31 | if (keyProperty == null) return null; 32 | var databaseGeneratedAttribute = keyProperty.GetCustomAttribute(typeof(DatabaseGeneratedAttribute)) as DatabaseGeneratedAttribute; 33 | if (databaseGeneratedAttribute?.DatabaseGeneratedOption != DatabaseGeneratedOption.Identity) return null; 34 | 35 | var entityArgument = Expression.Parameter(typeof(T)); 36 | var keyContextArgument = Expression.Parameter(typeof(KeyContext)); 37 | 38 | if (keyProperty.PropertyType == typeof(int)) 39 | { 40 | return BuildIdentityKeyFactory(keyProperty, ctx => Expression.Property(ctx, nameof(KeyContext.NextIdentity))); 41 | } 42 | else if (keyProperty.PropertyType == typeof(long)) 43 | { 44 | return BuildIdentityKeyFactory(keyProperty, ctx => Expression.Property(ctx, nameof(KeyContext.NextIdentity))); 45 | } 46 | else if (keyProperty.PropertyType == typeof(Guid)) 47 | { 48 | return BuildIdentityKeyFactory(keyProperty, _ => Expression.Call(typeof(Guid), nameof(Guid.NewGuid), Array.Empty())); 49 | } 50 | 51 | return null; 52 | } 53 | 54 | private static Func BuildIdentityKeyFactory( 55 | PropertyInfo keyProperty, 56 | Func nextIdentity) 57 | { 58 | var entityArgument = Expression.Parameter(typeof(TEntity)); 59 | var keyContextArgument = Expression.Parameter(typeof(KeyContext)); 60 | var keyValueVariable = Expression.Variable(typeof(TKey)); 61 | var body = Expression.Block(typeof(object), 62 | new[] { keyValueVariable }, 63 | Expression.Assign(keyValueVariable, Expression.Convert(Expression.Property(entityArgument, keyProperty), typeof(TKey))), 64 | Expression.IfThen(Expression.Equal(keyValueVariable, Expression.Default(typeof(TKey))), 65 | Expression.Block( 66 | Expression.Assign(keyValueVariable, Expression.Convert(nextIdentity(keyContextArgument), typeof(TKey))), 67 | Expression.Assign(Expression.Property(entityArgument, keyProperty), keyValueVariable) 68 | ) 69 | ), 70 | Expression.Convert(keyValueVariable, typeof(object))); 71 | 72 | return Expression.Lambda>(body, entityArgument, keyContextArgument).Compile(); 73 | } 74 | 75 | private static Func BuildDefaultKeyFactory(PropertyInfo[] keyProperties) 76 | { 77 | var entityType = typeof(T); 78 | 79 | var tupleType = Type.GetType($"System.Tuple`{keyProperties.Length}"); 80 | if (tupleType == null) throw new InvalidOperationException($"No tuple type found for {keyProperties.Length} generic arguments"); 81 | 82 | var keyPropertyTypes = keyProperties.Select(x => x.PropertyType).ToArray(); 83 | var constructor = tupleType.MakeGenericType(keyPropertyTypes).GetConstructor(keyPropertyTypes); 84 | if (constructor == null) throw new InvalidOperationException($"No tuple constructor found for key in {entityType.Name} entity"); 85 | 86 | var entityArgument = Expression.Parameter(entityType); 87 | var keyContextArgument = Expression.Parameter(typeof(KeyContext)); 88 | var newTupleExpression = Expression.New(constructor, keyProperties.Select(x => Expression.Property(entityArgument, x))); 89 | return Expression.Lambda>(newTupleExpression, entityArgument, keyContextArgument).Compile(); 90 | } 91 | } 92 | } 93 | -------------------------------------------------------------------------------- /src/EntityFrameworkCoreMock.Shared/KeyFactoryNormalizer.cs: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2017-2021 Wouter Huysentruit 3 | * 4 | * See LICENSE file. 5 | */ 6 | 7 | using System; 8 | using System.Linq; 9 | using System.Reflection; 10 | 11 | namespace EntityFrameworkCoreMock 12 | { 13 | internal sealed class KeyFactoryNormalizer 14 | where TEntity : class 15 | { 16 | private readonly Func _keyFactory; 17 | 18 | public KeyFactoryNormalizer(Func keyFactory) 19 | { 20 | _keyFactory = keyFactory; 21 | } 22 | 23 | public object GenerateKey(TEntity entity, KeyContext keyContext) 24 | => NormalizeKey(_keyFactory(entity, keyContext)); 25 | 26 | private static object NormalizeKey(object key) 27 | { 28 | var keyType = key?.GetType(); 29 | if (keyType == null) return null; 30 | 31 | if (keyType.FullName?.StartsWith("System.ValueTuple`") ?? false) 32 | { 33 | var valueTupleTypes = keyType.GetGenericArguments(); 34 | var toTupleMethod = typeof(TupleExtensions).GetMethods(BindingFlags.Public | BindingFlags.Static) 35 | .FirstOrDefault(x => x.Name.Equals(nameof(TupleExtensions.ToTuple)) && x.ReturnType.Name.Equals($"Tuple`{valueTupleTypes.Length}")); 36 | if (toTupleMethod == null) throw new InvalidOperationException($"No {nameof(TupleExtensions.ToTuple)} extension method found"); 37 | toTupleMethod = toTupleMethod?.MakeGenericMethod(valueTupleTypes); 38 | return toTupleMethod.Invoke(null, new[] { key }); 39 | } 40 | 41 | if (!keyType.FullName?.StartsWith("System.Tuple`") ?? false) 42 | { 43 | var tupleType = Type.GetType("System.Tuple`1"); 44 | if (tupleType == null) throw new InvalidOperationException($"No tuple type found for one generic arguments"); 45 | var constructor = tupleType.MakeGenericType(keyType).GetConstructor(new[] { keyType }); 46 | if (constructor == null) throw new InvalidOperationException($"No tuple constructor found for key in entity"); 47 | return constructor.Invoke(new[] { key }); 48 | } 49 | 50 | return key; 51 | } 52 | } 53 | } 54 | -------------------------------------------------------------------------------- /src/EntityFrameworkCoreMock.Shared/SavedChangesEventArgs.cs: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2017-2021 Wouter Huysentruit 3 | * 4 | * See LICENSE file. 5 | */ 6 | 7 | using System; 8 | 9 | namespace EntityFrameworkCoreMock 10 | { 11 | public sealed class SavedChangesEventArgs : EventArgs 12 | where TEntity : class 13 | { 14 | public UpdatedEntityInfo[] UpdatedEntities { get; set; } 15 | } 16 | 17 | public sealed class UpdatedEntityInfo 18 | where TEntity : class 19 | { 20 | public TEntity Entity { get; set; } 21 | 22 | public UpdatePropertyInfo[] UpdatedProperties { get; set; } 23 | } 24 | 25 | public sealed class UpdatePropertyInfo 26 | { 27 | public string Name { get; set; } 28 | 29 | public object Original { get; set; } 30 | 31 | public object New { get; set; } 32 | } 33 | } 34 | -------------------------------------------------------------------------------- /tests/Directory.Build.props: -------------------------------------------------------------------------------- 1 | 2 | 3 | net5.0 4 | false 5 | true 6 | false 7 | ../../Signing.snk 8 | 9 | 10 | -------------------------------------------------------------------------------- /tests/EntityFrameworkCoreMock.Moq.Tests/AutoMapperRelatedTests.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Linq; 3 | using System.Threading.Tasks; 4 | using AutoMapper; 5 | using AutoMapper.QueryableExtensions; 6 | using EntityFrameworkCoreMock.Tests.Models; 7 | using Microsoft.EntityFrameworkCore; 8 | using NUnit.Framework; 9 | 10 | namespace EntityFrameworkCoreMock.Moq.Tests 11 | { 12 | [TestFixture] 13 | public class AutoMapperRelatedTests 14 | { 15 | public class UserModel 16 | { 17 | public string FullName { get; set; } 18 | 19 | public string Name { get; set; } 20 | } 21 | 22 | [Test] 23 | public async Task DbSetMock_AutoMapperProjectTo() 24 | { 25 | var mapperConfiguration = new MapperConfiguration(config => 26 | { 27 | config 28 | .CreateMap() 29 | .ForMember(d => d.Name, opt => opt.MapFrom(s => s.FullName)); 30 | }); 31 | 32 | var dbSetMock = new DbSetMock(new[] 33 | { 34 | new User { Id = Guid.NewGuid(), FullName = "Fake Drake" }, 35 | new User { Id = Guid.NewGuid(), FullName = "Jackira Spicy" } 36 | }, (x, _) => x.Id); 37 | var dbSet = dbSetMock.Object; 38 | 39 | Assert.That(await dbSet.CountAsync(), Is.EqualTo(2)); 40 | 41 | var models = await dbSet 42 | .Where(u => u.FullName != null) 43 | .ProjectTo(mapperConfiguration) 44 | .ToListAsync(); 45 | 46 | Assert.That(models.Count, Is.EqualTo(2)); 47 | } 48 | } 49 | } 50 | -------------------------------------------------------------------------------- /tests/EntityFrameworkCoreMock.Moq.Tests/DbContextMockTests.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Linq; 3 | using System.Threading; 4 | using System.Threading.Tasks; 5 | using EntityFrameworkCoreMock.Tests.Models; 6 | using Microsoft.EntityFrameworkCore; 7 | using Microsoft.EntityFrameworkCore.ChangeTracking.Internal; 8 | using Microsoft.EntityFrameworkCore.Internal; 9 | using Moq; 10 | using NUnit.Framework; 11 | 12 | namespace EntityFrameworkCoreMock.Tests 13 | { 14 | [TestFixture] 15 | public class DbContextMockTests 16 | { 17 | [Test] 18 | public void DbContextMock_Constructor_PassDbContextOptions_ShouldPassDbContextOptionsToMockedClass() 19 | { 20 | var dbContextMock = new DbContextMock(Options); 21 | Assert.That(dbContextMock.Object.Options, Is.EqualTo(Options)); 22 | } 23 | 24 | [Test] 25 | public async Task DbContextMock_Constructor_ShouldSetupSaveChanges() 26 | { 27 | var dbContextMock = new DbContextMock(Options); 28 | dbContextMock.RegisterDbSetMock(x => x.Users, new TestDbSetMock()); 29 | Assert.That(dbContextMock.Object.SaveChanges(), Is.EqualTo(55861)); 30 | Assert.That(await dbContextMock.Object.SaveChangesAsync(), Is.EqualTo(55861)); 31 | Assert.That(await dbContextMock.Object.SaveChangesAsync(CancellationToken.None), Is.EqualTo(55861)); 32 | } 33 | 34 | [Test] 35 | public void DbContextMock_Reset_ShouldForgetMockedDbSets() 36 | { 37 | var dbContextMock = new DbContextMock(Options); 38 | dbContextMock.RegisterDbSetMock(x => x.Users, new TestDbSetMock()); 39 | Assert.That(dbContextMock.Object.SaveChanges(), Is.EqualTo(55861)); 40 | dbContextMock.Reset(); 41 | Assert.That(dbContextMock.Object.SaveChanges(), Is.EqualTo(0)); 42 | } 43 | 44 | [Test] 45 | public void DbContextMock_Reset_ShouldResetupSaveChanges() 46 | { 47 | var dbContextMock = new DbContextMock(Options); 48 | dbContextMock.RegisterDbSetMock(x => x.Users, new TestDbSetMock()); 49 | Assert.That(dbContextMock.Object.SaveChanges(), Is.EqualTo(55861)); 50 | dbContextMock.Reset(); 51 | Assert.That(dbContextMock.Object.SaveChanges(), Is.EqualTo(0)); 52 | dbContextMock.RegisterDbSetMock(x => x.Users, new TestDbSetMock()); 53 | Assert.That(dbContextMock.Object.SaveChanges(), Is.EqualTo(55861)); 54 | } 55 | 56 | [Test] 57 | public void DbContextMock_CreateDbSetMock_CreateIdenticalDbSetMockTwice_ShouldThrowExceptionSecondTime() 58 | { 59 | var dbContextMock = new DbContextMock(Options); 60 | dbContextMock.CreateDbSetMock(x => x.Users); 61 | var ex = Assert.Throws(() => dbContextMock.CreateDbSetMock(x => x.Users)); 62 | Assert.That(ex.ParamName, Is.EqualTo("dbSetSelector")); 63 | Assert.That(ex.Message, Does.StartWith("DbSetMock for entity User already created")); 64 | } 65 | 66 | [Test] 67 | public void DbContextMock_CreateDbSetMock_ShouldSetupMockForDbSetSelector() 68 | { 69 | var dbContextMock = new DbContextMock(Options); 70 | Assert.That(dbContextMock.Object.Users, Is.Null); 71 | dbContextMock.CreateDbSetMock(x => x.Users); 72 | Assert.That(dbContextMock.Object.Users, Is.Not.Null); 73 | } 74 | 75 | [Test] 76 | public async Task DbContextMock_CreateDbSetMock_PassInitialEntities_DbSetShouldContainInitialEntities() 77 | { 78 | var dbContextMock = new DbContextMock(Options); 79 | dbContextMock.CreateDbSetMock(x => x.Users, new[] 80 | { 81 | new User { Id = Guid.NewGuid(), FullName = "Eric Cartoon" }, 82 | new User { Id = Guid.NewGuid(), FullName = "Billy Jewel" }, 83 | }); 84 | 85 | Assert.That(dbContextMock.Object.Users.Count(), Is.EqualTo(2)); 86 | Assert.That(await dbContextMock.Object.Users.CountAsync(), Is.EqualTo(2)); 87 | 88 | var result = await dbContextMock.Object.Users.FirstAsync(x => x.FullName.StartsWith("Eric")); 89 | Assert.That(result.FullName, Is.EqualTo("Eric Cartoon")); 90 | 91 | result = dbContextMock.Object.Users.First(x => x.FullName.Contains("Jewel")); 92 | Assert.That(result.FullName, Is.EqualTo("Billy Jewel")); 93 | } 94 | 95 | [Test] 96 | public void DbContextMock_CreateDbSetMock_NoKeyFactoryForModelWithoutId_ShouldThrowException() 97 | { 98 | // Arrange 99 | var dbContextMock = new DbContextMock(Options); 100 | 101 | // Act & Assert 102 | var ex = Assert.Throws(() => dbContextMock.CreateDbSetMock(x => x.NoKeyModels)); 103 | Assert.That(ex.Message, Does.StartWith("No key factory could be created for entity type NoKeyModel, see inner exceptions")); 104 | } 105 | 106 | [Test] 107 | public void DbContextMock_CreateDbSetMock_PassCustomKeyFactoryForModelWithoutId_ShouldNotThrowException() 108 | { 109 | var dbContextMock = new DbContextMock(Options); 110 | Assert.DoesNotThrow(() => dbContextMock.CreateDbSetMock(x => x.NoKeyModels, (x, _) => x.ModelId)); 111 | } 112 | 113 | [Test] 114 | public void DbContextMock_CreateDbSetMock_KeylessModel_ShouldNotThrowException() 115 | { 116 | var dbContextMock = new DbContextMock(Options); 117 | Assert.DoesNotThrow(() => dbContextMock.CreateDbSetMock(x => x.NoKeyModels, (x, _) => x, new NoKeyModel[] { new NoKeyModel() })); 118 | } 119 | 120 | [Test] 121 | public void DbContextMock_CreateDbSetMock_ModelWithProtectedProperties_ShouldNotThrowException() 122 | { 123 | var dbContextMock = new DbContextMock(Options); 124 | Assert.DoesNotThrow(() => dbContextMock.CreateDbSetMock(x => 125 | x.ProtectedSetterPropertyModels, (x, _) => x, new[] { new ProtectedSetterPropertyModel() })); 126 | } 127 | 128 | [Ignore("Not yet ported to EntityFrameworkCoreMock")] 129 | public void DbContextMock_CreateDbSetMock_AddModelWithSameKeyTwice_ShouldThrowDbUpdatedException() 130 | { 131 | var userId = Guid.NewGuid(); 132 | var dbContextMock = new DbContextMock(Options); 133 | var dbSetMock = dbContextMock.CreateDbSetMock(x => x.Users); 134 | dbSetMock.Object.Add(new User { Id = userId, FullName = "SomeName" }); 135 | dbSetMock.Object.Add(new User { Id = Guid.NewGuid(), FullName = "SomeName" }); 136 | dbContextMock.Object.SaveChanges(); 137 | dbSetMock.Object.Add(new User { Id = userId, FullName = "SomeName" }); 138 | Assert.Throws(() => dbContextMock.Object.SaveChanges()); 139 | } 140 | 141 | [Ignore("Not yet ported to EntityFrameworkCoreMock")] 142 | public void DbContextMock_CreateDbSetMock_DeleteUnknownModel_ShouldThrowDbUpdateConcurrencyException() 143 | { 144 | var dbContextMock = new DbContextMock(Options); 145 | var dbSetMock = dbContextMock.CreateDbSetMock(x => x.Users); 146 | dbSetMock.Object.Remove(new User { Id = Guid.NewGuid() }); 147 | Assert.Throws(() => dbContextMock.Object.SaveChanges()); 148 | } 149 | 150 | [Test] 151 | public void DbContextMock_CreateDbSetMock_AddMultipleModelsWithDatabaseGeneratedIdentityKey_ShouldGenerateSequentialKey() 152 | { 153 | var dbContextMock = new DbContextMock(Options); 154 | var dbSetMock = dbContextMock.CreateDbSetMock(x => x.GeneratedKeyModels, new[] 155 | { 156 | new GeneratedKeyModel {Value = "first"}, 157 | new GeneratedKeyModel {Value = "second"} 158 | }); 159 | dbSetMock.Object.Add(new GeneratedKeyModel { Value = "third" }); 160 | dbContextMock.Object.SaveChanges(); 161 | 162 | Assert.That(dbSetMock.Object.Min(x => x.Id), Is.EqualTo(1)); 163 | Assert.That(dbSetMock.Object.Max(x => x.Id), Is.EqualTo(3)); 164 | Assert.That(dbSetMock.Object.First(x => x.Id == 1).Value, Is.EqualTo("first")); 165 | Assert.That(dbSetMock.Object.First(x => x.Id == 2).Value, Is.EqualTo("second")); 166 | Assert.That(dbSetMock.Object.First(x => x.Id == 3).Value, Is.EqualTo("third")); 167 | } 168 | 169 | [Test] 170 | public void DbContextMock_CreateDbSetMock_AddMultipleModelsWithGuidAsDatabaseGeneratedIdentityKey_ShouldGenerateRandomGuidAsKey() 171 | { 172 | var knownId = Guid.NewGuid(); 173 | var dbContextMock = new DbContextMock(Options); 174 | var dbSetMock = dbContextMock.CreateDbSetMock(x => x.GeneratedGuidKeyModels, new[] 175 | { 176 | new GeneratedGuidKeyModel {Id = knownId, Value = "first"}, 177 | new GeneratedGuidKeyModel {Value = "second"} 178 | }); 179 | dbSetMock.Object.Add(new GeneratedGuidKeyModel { Value = "third" }); 180 | dbContextMock.Object.SaveChanges(); 181 | 182 | var modelWithKnownId = dbSetMock.Object.FirstOrDefault(x => x.Id == knownId); 183 | Assert.That(modelWithKnownId, Is.Not.Null); 184 | Assert.That(modelWithKnownId.Value, Is.EqualTo("first")); 185 | } 186 | 187 | [Test] 188 | public async Task DbContextMock_CreateDbSetMock_AsyncAddMultipleModelsWithLongAsDatabaseGeneratedIdentityKey_ShouldGenerateIncrementalKey() 189 | { 190 | // Arrange 191 | var dbContextMock = new DbContextMock(Options); 192 | var dbSetMock = dbContextMock.CreateDbSetMock(x => x.Issue20Models); 193 | 194 | // Act 195 | await dbContextMock.Object.Issue20Models.AddAsync(new Issue20Model { Url = "A" }); 196 | await dbContextMock.Object.Issue20Models.AddAsync(new Issue20Model { Url = "B" }); 197 | await dbContextMock.Object.Issue20Models.AddAsync(new Issue20Model { Url = "C" }); 198 | await dbContextMock.Object.SaveChangesAsync(); 199 | 200 | // Assert 201 | Assert.That(dbSetMock.Object.First(x => x.Url == "A").LoggingRepositoryId, Is.EqualTo(1)); 202 | Assert.That(dbSetMock.Object.First(x => x.Url == "B").LoggingRepositoryId, Is.EqualTo(2)); 203 | Assert.That(dbSetMock.Object.First(x => x.Url == "C").LoggingRepositoryId, Is.EqualTo(3)); 204 | } 205 | 206 | [Test] 207 | public void DbContextMock_CreateDbSetMock_GenericDbSetSelector_ShouldReturnDbSetMock() 208 | { 209 | var dbContextMock = new DbContextMock(Options); 210 | var dbSetMock = dbContextMock.CreateDbSetMock(x => x.Set()); 211 | Assert.That(dbSetMock.Object, Is.Not.Null); 212 | } 213 | 214 | [Test] 215 | public void DbContextMock_GenericSet_ShouldReturnDbSetMock() 216 | { 217 | var dbContextMock = new DbContextMock(Options); 218 | var dbSetMock = dbContextMock.CreateDbSetMock(x => x.Users); 219 | var dbSet = dbContextMock.Object.Set(); 220 | Assert.That(dbSet, Is.Not.Null); 221 | Assert.That(dbSet, Is.EqualTo(dbSetMock.Object)); 222 | } 223 | 224 | [Test] 225 | public void DbContextMock_GenericSet_AsQueryable_ShouldReturnQueryable() 226 | { 227 | var dbContextMock = new DbContextMock(Options); 228 | dbContextMock.CreateDbSetMock(x => x.Users); 229 | var dbSet = dbContextMock.Object.Set(); 230 | Assert.That(dbSet.AsQueryable(), Is.Not.Null); 231 | } 232 | 233 | [Test] 234 | public void DbContextMock_BeginTransaction_CommitTransaction_ShouldNotFail() 235 | { 236 | var dbContextMock = new DbContextMock(Options); 237 | Assert.DoesNotThrow(() => 238 | { 239 | var transaction = dbContextMock.Object.Database.BeginTransaction(); 240 | transaction.Commit(); 241 | transaction.Rollback(); 242 | }); 243 | 244 | Assert.DoesNotThrowAsync(async () => 245 | { 246 | var transaction = await dbContextMock.Object.Database.BeginTransactionAsync(); 247 | await transaction.CommitAsync(); 248 | await transaction.RollbackAsync(); 249 | }); 250 | } 251 | 252 | [Test] 253 | public void DbContextMock_Add_ShouldAddEntity() 254 | { 255 | var dbContextMock = new DbContextMock(Options); 256 | var user = new User { Id = Guid.NewGuid(), FullName = "Mark Kramer" }; 257 | dbContextMock.CreateDbSetMock(x => x.Users, Array.Empty()); 258 | 259 | dbContextMock.Object.Add(user); 260 | dbContextMock.Object.SaveChanges(); 261 | 262 | var dbSet = dbContextMock.Object.Users; 263 | Assert.That(dbSet.Count(), Is.EqualTo(1)); 264 | var actualUser = dbSet.First(); 265 | Assert.That(actualUser, Is.Not.Null); 266 | Assert.That(actualUser.FullName, Is.EqualTo("Mark Kramer")); 267 | } 268 | 269 | [Test] 270 | public async Task DbContextMock_AddAsync_ShouldAddEntity() 271 | { 272 | var dbContextMock = new DbContextMock(Options); 273 | var user = new User { Id = Guid.NewGuid(), FullName = "Mark Kramer" }; 274 | dbContextMock.CreateDbSetMock(x => x.Users, Array.Empty()); 275 | 276 | await dbContextMock.Object.AddAsync(user); 277 | await dbContextMock.Object.SaveChangesAsync(); 278 | 279 | var dbSet = dbContextMock.Object.Users; 280 | Assert.That(dbSet.Count(), Is.EqualTo(1)); 281 | var actualUser = dbSet.First(); 282 | Assert.That(actualUser, Is.Not.Null); 283 | Assert.That(actualUser.FullName, Is.EqualTo("Mark Kramer")); 284 | } 285 | 286 | [Test] 287 | public void DbContextMock_Update_ShouldUpdateEntity() 288 | { 289 | var dbContextMock = new DbContextMock(Options); 290 | var user = new User { Id = Guid.NewGuid(), FullName = "Mark Kramer" }; 291 | dbContextMock.CreateDbSetMock(x => x.Users, new[] { user }); 292 | 293 | dbContextMock.Object.Update(new User { Id = user.Id, FullName = "Updated name" }); 294 | dbContextMock.Object.SaveChanges(); 295 | 296 | var dbSet = dbContextMock.Object.Users; 297 | Assert.That(dbSet.Count(), Is.EqualTo(1)); 298 | var actualUser = dbSet.First(); 299 | Assert.That(actualUser, Is.Not.Null); 300 | Assert.That(actualUser.FullName, Is.EqualTo("Updated name")); 301 | } 302 | 303 | [Test] 304 | public void DbContextMock_Remove_ShouldRemoveEntity() 305 | { 306 | var dbContextMock = new DbContextMock(Options); 307 | var user = new User { Id = Guid.NewGuid(), FullName = "Mark Kramer" }; 308 | dbContextMock.CreateDbSetMock(x => x.Users, new[] { user }); 309 | 310 | dbContextMock.Object.Remove(user); 311 | dbContextMock.Object.SaveChanges(); 312 | 313 | var dbSet = dbContextMock.Object.Users; 314 | Assert.That(dbSet.Count(), Is.EqualTo(0)); 315 | } 316 | 317 | [Test] 318 | #pragma warning disable EF1001 // Remove warning for use of internal EF Core infrastructure 319 | public void DbContextMock_AdditionalMockSetupAfterConstruction_ShouldNotThrow() 320 | { 321 | // Arrange 322 | var dbContextMock = new DbContextMock(Options); 323 | 324 | // Act & Assert 325 | Assert.DoesNotThrow(() => 326 | { 327 | dbContextMock.As() 328 | .Setup(x => x.StateManager) 329 | .Returns(Mock.Of()); 330 | }); 331 | } 332 | #pragma warning restore EF1001 333 | 334 | [Test] 335 | #pragma warning disable EF1001 // Remove warning for use of internal EF Core infrastructure 336 | public void DbContextMock_AdditionalMockSetupAfterConstruction_ShouldUseAdditionalMockSetup() 337 | { 338 | // Arrange 339 | var stateManager = Mock.Of(); 340 | var dbContextMock = new DbContextMock(Options); 341 | 342 | // Act 343 | dbContextMock.As() 344 | .Setup(x => x.StateManager) 345 | .Returns(stateManager); 346 | 347 | // Assert 348 | Assert.That(((IDbContextDependencies)dbContextMock.Object).StateManager, Is.EqualTo(stateManager)); 349 | } 350 | #pragma warning restore EF1001 351 | 352 | public class TestDbSetMock : IDbSetMock 353 | { 354 | public int SaveChanges() => 55861; 355 | } 356 | 357 | public DbContextOptions Options { get; } = new DbContextOptionsBuilder().Options; 358 | 359 | public class TestDbContext : DbContext 360 | { 361 | public TestDbContext(DbContextOptions options) 362 | : base(options) 363 | { 364 | Options = options; 365 | } 366 | 367 | public DbContextOptions Options { get; } 368 | 369 | public virtual DbSet Users { get; set; } 370 | 371 | public virtual DbSet NoKeyModels { get; set; } 372 | 373 | public virtual DbSet ProtectedSetterPropertyModels { get; set; } 374 | 375 | public virtual DbSet GeneratedKeyModels { get; set; } 376 | 377 | public virtual DbSet GeneratedGuidKeyModels { get; set; } 378 | 379 | public virtual DbSet Issue20Models { get; set; } 380 | } 381 | } 382 | } 383 | -------------------------------------------------------------------------------- /tests/EntityFrameworkCoreMock.Moq.Tests/DbSetMockTests.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.ComponentModel.DataAnnotations.Schema; 4 | using System.Linq; 5 | using System.Threading.Tasks; 6 | using EntityFrameworkCoreMock.Tests.Models; 7 | using Microsoft.EntityFrameworkCore; 8 | using NUnit.Framework; 9 | 10 | namespace EntityFrameworkCoreMock.Tests 11 | { 12 | [TestFixture] 13 | public class DbSetMockTests 14 | { 15 | [Test] 16 | public void DbSetMock_AsNoTracking_ShouldForwardProvider() 17 | { 18 | var dbSetMock = new DbSetMock(null, (x, _) => x.Id); 19 | var dbSet = dbSetMock.Object; 20 | Assert.That(dbSet.AsNoTracking().Provider, Is.EqualTo(((IQueryable)dbSet).Provider)); 21 | } 22 | 23 | [Test] 24 | public void DbSetMock_AsQueryable_ShouldReturnQueryable() 25 | { 26 | var dbSetMock = new DbSetMock(null, (x, _) => x.Id); 27 | var dbSet = dbSetMock.Object; 28 | Assert.That(dbSet.AsQueryable(), Is.Not.Null); 29 | } 30 | 31 | [Test] 32 | public void DbSetMock_Include_ShouldForwardProvider() 33 | { 34 | var dbSetMock = new DbSetMock(null, (x, _) => x.Id); 35 | var dbSet = dbSetMock.Object; 36 | Assert.That(dbSet.Include(x => x.User).Provider, Is.EqualTo(((IQueryable)dbSet).Provider)); 37 | } 38 | 39 | [Test] 40 | public void DbSetMock_GivenEntityIsAdded_ShouldAddAfterCallingSaveChanges() 41 | { 42 | var user = new User { Id = Guid.NewGuid(), FullName = "Fake Drake" }; 43 | var dbSetMock = new DbSetMock(null, (x, _) => x.Id); 44 | var dbSet = dbSetMock.Object; 45 | 46 | Assert.That(dbSet.Count(), Is.EqualTo(0)); 47 | dbSet.Add(user); 48 | Assert.That(dbSet.Count(), Is.EqualTo(0)); 49 | ((IDbSetMock)dbSetMock).SaveChanges(); 50 | Assert.That(dbSet.Count(), Is.EqualTo(1)); 51 | Assert.That(dbSet.Any(x => x.Id == user.Id && x.FullName == user.FullName), Is.True); 52 | } 53 | 54 | [Test] 55 | public void DbSetMock_GivenEntityRangeIsAdded_ShouldAddAfterCallingSaveChanges() 56 | { 57 | // Arrange 58 | var users = new[] 59 | { 60 | new User { Id = Guid.NewGuid(), FullName = "Ian Kilmister" }, 61 | new User { Id = Guid.NewGuid(), FullName = "Phil Taylor" }, 62 | new User { Id = Guid.NewGuid(), FullName = "Eddie Clarke" } 63 | }; 64 | var dbSetMock = new DbSetMock(null, (x, _) => x.Id); 65 | var dbSet = dbSetMock.Object; 66 | 67 | Assert.That(dbSet.Count(), Is.EqualTo(0)); 68 | 69 | // Act 70 | dbSet.AddRange(users); 71 | ((IDbSetMock)dbSetMock).SaveChanges(); 72 | 73 | // Assert 74 | var firstUser = users.First(); 75 | Assert.That(dbSet.Count(), Is.EqualTo(3)); 76 | Assert.That(dbSet.Any(x => x.Id == firstUser.Id 77 | && x.FullName == firstUser.FullName), Is.True); 78 | } 79 | 80 | [Test] 81 | public void DbSetMock_GivenEntityIsUpdated_ShouldUpdateAfterCallingSaveChanges() 82 | { 83 | var user = new User { Id = Guid.NewGuid(), FullName = "Fake Drake" }; 84 | var dbSetMock = new DbSetMock(new[] { user }, (x, _) => x.Id); 85 | var dbSet = dbSetMock.Object; 86 | 87 | dbSet.Update(new User { Id = user.Id, FullName = "Fake Snake" }); 88 | Assert.That(dbSet.First().FullName, Is.EqualTo("Fake Drake")); 89 | ((IDbSetMock)dbSetMock).SaveChanges(); 90 | Assert.That(dbSet.Count(), Is.EqualTo(1)); 91 | Assert.That(dbSet.First().FullName, Is.EqualTo("Fake Snake")); 92 | } 93 | 94 | [Test] 95 | public void DbSetMock_GivenEntityRangeIsUpdated_ShouldUpdateAfterCallingSaveChanges() 96 | { 97 | // Arrange 98 | var users = new[] 99 | { 100 | new User { Id = Guid.NewGuid(), FullName = "Ian Kilmister" }, 101 | new User { Id = Guid.NewGuid(), FullName = "Phil Taylor" }, 102 | new User { Id = Guid.NewGuid(), FullName = "Eddie Clarke" } 103 | }; 104 | var dbSetMock = new DbSetMock(users, (x, _) => x.Id); 105 | var dbSet = dbSetMock.Object; 106 | 107 | // Act 108 | dbSet.UpdateRange(new[] 109 | { 110 | new User { Id = users[0].Id, FullName = "Ian Kilmister AAA" }, 111 | new User { Id = users[1].Id, FullName = "Phil Taylor AAA" }, 112 | new User { Id = users[2].Id, FullName = "Eddie Clarke AAA" } 113 | }); 114 | ((IDbSetMock)dbSetMock).SaveChanges(); 115 | 116 | // Assert 117 | Assert.That(dbSet.Count(), Is.EqualTo(3)); 118 | Assert.That(dbSet.All(x => x.FullName.EndsWith("AAA")), Is.True); 119 | } 120 | 121 | [Test] 122 | public async Task DbSetMock_AsyncProvider() 123 | { 124 | var user = new User { Id = Guid.NewGuid(), FullName = "Fake Drake" }; 125 | var dbSetMock = new DbSetMock(null, (x, _) => x.Id); 126 | var dbSet = dbSetMock.Object; 127 | 128 | Assert.That(await dbSet.CountAsync(), Is.EqualTo(0)); 129 | dbSet.Add(user); 130 | Assert.That(await dbSet.CountAsync(), Is.EqualTo(0)); 131 | ((IDbSetMock)dbSetMock).SaveChanges(); 132 | Assert.That(await dbSet.CountAsync(), Is.EqualTo(1)); 133 | Assert.That(await dbSet.AnyAsync(x => x.Id == user.Id && x.FullName == user.FullName), Is.True); 134 | } 135 | 136 | [Test] 137 | public void DbSetMock_GivenEntityIsRemoved_ShouldRemoveAfterCallingSaveChanges() 138 | { 139 | var user = new User { Id = Guid.NewGuid(), FullName = "Fake Drake" }; 140 | var dbSetMock = new DbSetMock(new[] 141 | { 142 | user, 143 | new User {Id = Guid.NewGuid(), FullName = "Jackira Spicy"} 144 | }, (x, _) => x.Id); 145 | var dbSet = dbSetMock.Object; 146 | 147 | Assert.That(dbSet.Count(), Is.EqualTo(2)); 148 | dbSet.Remove(new User { Id = user.Id }); 149 | Assert.That(dbSet.Count(), Is.EqualTo(2)); 150 | Assert.That(dbSet.Any(x => x.Id == user.Id && x.FullName == user.FullName), Is.True); 151 | ((IDbSetMock)dbSetMock).SaveChanges(); 152 | Assert.That(dbSet.Count(), Is.EqualTo(1)); 153 | Assert.That(dbSet.Any(x => x.Id == user.Id && x.FullName == user.FullName), Is.False); 154 | } 155 | 156 | [Test] 157 | public void DbSetMock_GivenRangeOfEntitiesIsRemoved_ShouldRemoveAfterCallingSaveChanges() 158 | { 159 | var users = new[] 160 | { 161 | new User {Id = Guid.NewGuid(), FullName = "User 1"}, 162 | new User {Id = Guid.NewGuid(), FullName = "User 2"}, 163 | new User {Id = Guid.NewGuid(), FullName = "User 3"} 164 | }; 165 | var dbSetMock = new DbSetMock(users, (x, _) => x.Id); 166 | var dbSet = dbSetMock.Object; 167 | 168 | Assert.That(dbSet.Count(), Is.EqualTo(3)); 169 | dbSet.RemoveRange(users.Skip(1)); 170 | Assert.That(dbSet.Count(), Is.EqualTo(3)); 171 | ((IDbSetMock)dbSetMock).SaveChanges(); 172 | Assert.That(dbSet.Count(), Is.EqualTo(1)); 173 | Assert.That(dbSet.Any(x => x.FullName == "User 1"), Is.True); 174 | Assert.That(dbSet.Any(x => x.FullName == "User 2"), Is.False); 175 | } 176 | 177 | [Test] 178 | public void DbSetMock_SaveChanges_GivenEntityPropertyIsChanged_ShouldFireSavedChangesEventWithCorrectUpdatedInfo() 179 | { 180 | var userId = Guid.NewGuid(); 181 | var dbSetMock = new DbSetMock(new[] 182 | { 183 | new User {Id = userId, FullName = "Mark Kramer"}, 184 | new User {Id = Guid.NewGuid(), FullName = "Freddy Kipcurry"} 185 | }, (x, _) => x.Id); 186 | var dbSet = dbSetMock.Object; 187 | 188 | Assert.That(dbSet.Count(), Is.EqualTo(2)); 189 | var fetchedUser = dbSet.First(x => x.Id == userId); 190 | fetchedUser.FullName = "Kramer Mark"; 191 | 192 | SavedChangesEventArgs eventArgs = null; 193 | dbSetMock.SavedChanges += (sender, args) => eventArgs = args; 194 | 195 | ((IDbSetMock)dbSetMock).SaveChanges(); 196 | 197 | Assert.That(eventArgs, Is.Not.Null); 198 | Assert.That(eventArgs.UpdatedEntities, Has.Length.EqualTo(1)); 199 | var updatedEntity = eventArgs.UpdatedEntities[0]; 200 | Assert.That(updatedEntity.UpdatedProperties, Has.Length.EqualTo(1)); 201 | var updatedProperty = updatedEntity.UpdatedProperties[0]; 202 | Assert.That(updatedProperty.Name, Is.EqualTo("FullName")); 203 | Assert.That(updatedProperty.Original, Is.EqualTo("Mark Kramer")); 204 | Assert.That(updatedProperty.New, Is.EqualTo("Kramer Mark")); 205 | } 206 | 207 | [Test] 208 | public void DbSetMock_SaveChanges_GivenEntityPropertyMarkedAsNotMapped_ShouldNotMarkNotMappedPropertyAsModified() 209 | { 210 | var dbSetMock = new DbSetMock(new[] 211 | { 212 | new NestedModel {Id = Guid.NewGuid(), NestedDocument = new NestedModel.Document()}, 213 | new NestedModel {Id = Guid.NewGuid(), NestedDocument = new NestedModel.Document()}, 214 | new NestedModel {Id = Guid.NewGuid(), NestedDocument = new NestedModel.Document()} 215 | }, (x, _) => x.Id); 216 | 217 | SavedChangesEventArgs eventArgs = null; 218 | dbSetMock.SavedChanges += (sender, args) => eventArgs = args; 219 | 220 | dbSetMock.Object.First().Value = "abc"; 221 | 222 | ((IDbSetMock)dbSetMock).SaveChanges(); 223 | 224 | Assert.That(eventArgs, Is.Not.Null); 225 | Assert.That(eventArgs.UpdatedEntities, Has.Length.EqualTo(1)); 226 | Assert.That(eventArgs.UpdatedEntities.First().UpdatedProperties, Has.Length.EqualTo(1)); 227 | var updatedProperty = eventArgs.UpdatedEntities.First().UpdatedProperties.First(); 228 | Assert.That(updatedProperty.Name, Is.EqualTo("Value")); 229 | Assert.That(updatedProperty.Original, Is.EqualTo(null)); 230 | Assert.That(updatedProperty.New, Is.EqualTo("abc")); 231 | } 232 | 233 | [Test] 234 | public void DbSetMock_Empty_AsEnumerable_ShouldReturnEmptyEnumerable() 235 | { 236 | var dbSetMock = new DbSetMock(new List(), (x, _) => x.Id); 237 | var nestedModels = dbSetMock.Object.AsEnumerable(); 238 | Assert.That(nestedModels, Is.Not.Null); 239 | Assert.That(nestedModels, Is.Empty); 240 | } 241 | 242 | [Test] 243 | public void DbSetMock_AsEnumerable_ShouldReturnEnumerableCollection() 244 | { 245 | var dbSetMock = new DbSetMock(new[] 246 | { 247 | new NestedModel {Id = Guid.NewGuid(), NestedDocument = new NestedModel.Document()}, 248 | new NestedModel {Id = Guid.NewGuid(), NestedDocument = new NestedModel.Document()} 249 | }, (x, _) => x.Id); 250 | var nestedModels = dbSetMock.Object.AsEnumerable(); 251 | Assert.That(nestedModels, Is.Not.Null); 252 | Assert.That(nestedModels.Count(), Is.EqualTo(2)); 253 | } 254 | 255 | [Test] 256 | public async Task DbSetMock_AsyncProvider_ShouldReturnRequestedModel() 257 | { 258 | var userId = Guid.NewGuid(); 259 | var dbSetMock = new DbSetMock(new[] 260 | { 261 | new User {Id = userId, FullName = "Mark Kramer"}, 262 | new User {Id = Guid.NewGuid(), FullName = "Freddy Kipcurry"} 263 | }, (x, _) => x.Id); 264 | 265 | var model = await dbSetMock.Object.Where(x => x.Id == userId).FirstOrDefaultAsync(); 266 | Assert.That(model, Is.Not.Null); 267 | Assert.That(model.FullName, Is.EqualTo("Mark Kramer")); 268 | } 269 | 270 | [Test] 271 | public async Task DbSetMock_AsyncProvider_OrderBy_ShouldReturnRequestedModel() 272 | { 273 | var dbSetMock = new DbSetMock(new[] 274 | { 275 | new User {Id = Guid.NewGuid(), FullName = "Mark Kramer"}, 276 | new User {Id = Guid.NewGuid(), FullName = "Freddy Kipcurry"} 277 | }, (x, _) => x.Id); 278 | 279 | var result = await dbSetMock.Object.Where(x => x.Id != Guid.Empty).OrderBy(x => x.FullName).ToListAsync(); 280 | Assert.That(result, Is.Not.Null); 281 | Assert.That(result, Has.Count.EqualTo(2)); 282 | Assert.That(result.First().FullName, Is.EqualTo("Freddy Kipcurry")); 283 | } 284 | 285 | [Test] 286 | public void DbSetMock_Find_ShouldReturnRequestedModel() 287 | { 288 | Guid user1 = Guid.NewGuid(), user2 = Guid.NewGuid(); 289 | var dbSetMock = new DbSetMock(new[] 290 | { 291 | new User {Id = user1, FullName = "Mark Kramer"}, 292 | new User {Id = user2, FullName = "Freddy Kipcurry"} 293 | }, (x, _) => x.Id); 294 | 295 | var result = dbSetMock.Object.Find(user2); 296 | Assert.That(result, Is.Not.Null); 297 | Assert.That(result.FullName, Is.EqualTo("Freddy Kipcurry")); 298 | } 299 | 300 | [Test] 301 | public void DbSetMock_Find_UnknownId_ShouldReturnNull() 302 | { 303 | var unknownUser = Guid.NewGuid(); 304 | var dbSetMock = new DbSetMock(new[] 305 | { 306 | new User {Id = Guid.NewGuid(), FullName = "Mark Kramer"}, 307 | new User {Id = Guid.NewGuid(), FullName = "Freddy Kipcurry"} 308 | }, (x, _) => x.Id); 309 | 310 | var result = dbSetMock.Object.Find(unknownUser); 311 | Assert.That(result, Is.Null); 312 | } 313 | 314 | [Test] 315 | public void DbSetMock_FindOnCompositeTupleKey_ShouldReturnRequestedModel() 316 | { 317 | Guid modelId1 = Guid.NewGuid(), modelId2 = Guid.NewGuid(); 318 | var dbSetMock = new DbSetMock(new[] 319 | { 320 | new NoKeyModel {ModelId = modelId1, Value = "Value 1"}, 321 | new NoKeyModel {ModelId = modelId2, Value = "Value 2"} 322 | }, (x, _) => new Tuple(x.ModelId, x.Value)); 323 | 324 | var result = dbSetMock.Object.Find(modelId2, "Value 2"); 325 | Assert.That(result, Is.Not.Null); 326 | Assert.That(result.ModelId, Is.EqualTo(modelId2)); 327 | Assert.That(result.Value, Is.EqualTo("Value 2")); 328 | } 329 | 330 | [Test] 331 | public void DbSetMock_FindOnCompositeValueTupleKey_ShouldReturnRequestedModel() 332 | { 333 | Guid modelId1 = Guid.NewGuid(), modelId2 = Guid.NewGuid(); 334 | var dbSetMock = new DbSetMock(new[] 335 | { 336 | new NoKeyModel {ModelId = modelId1, Value = "Value 1"}, 337 | new NoKeyModel {ModelId = modelId2, Value = "Value 2"} 338 | }, (x, _) => (x.ModelId, x.Value)); 339 | 340 | var result = dbSetMock.Object.Find(modelId2, "Value 2"); 341 | Assert.That(result, Is.Not.Null); 342 | Assert.That(result.ModelId, Is.EqualTo(modelId2)); 343 | Assert.That(result.Value, Is.EqualTo("Value 2")); 344 | } 345 | 346 | public class NestedModel 347 | { 348 | public Guid Id { get; set; } 349 | 350 | public string Value { get; set; } 351 | 352 | [NotMapped] 353 | public Document NestedDocument 354 | { 355 | get { return new Document { Name = Guid.NewGuid().ToString("N") }; } 356 | // ReSharper disable once ValueParameterNotUsed 357 | set { } 358 | } 359 | 360 | public class Document 361 | { 362 | public string Name { get; set; } 363 | } 364 | } 365 | 366 | [Test] 367 | public void DbSetMock_SaveChanges_GivenAbstractEntityModel_ShouldNotThrowException() 368 | { 369 | var dbSetMock = new DbSetMock(new[] 370 | { 371 | new ConcreteModel {Id = Guid.NewGuid()} 372 | }, (x, _) => x.Id); 373 | 374 | ((IDbSetMock)dbSetMock).SaveChanges(); 375 | } 376 | 377 | public abstract class AbstractModel 378 | { 379 | public Guid Id { get; set; } 380 | } 381 | 382 | public class ConcreteModel : AbstractModel 383 | { 384 | public string Name { get; set; } = "SomeName"; 385 | } 386 | 387 | [Test] 388 | public void DbSetMock_ModelPropertyWithPrivateSetter_ShouldSetTheProperty() 389 | { 390 | var dbSetMock = new DbSetMock(new[] 391 | { 392 | new PrivateSetterPropertyModel("my value") 393 | }, (x, _) => x.Private); 394 | 395 | var dbSet = dbSetMock.Object; 396 | Assert.That(dbSet.First().Private, Is.EqualTo("my value")); 397 | } 398 | } 399 | } 400 | -------------------------------------------------------------------------------- /tests/EntityFrameworkCoreMock.Moq.Tests/EntityFrameworkCoreMock.Moq.Tests.csproj: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | -------------------------------------------------------------------------------- /tests/EntityFrameworkCoreMock.Moq.Tests/Models/GeneratedGuidKeyModel.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.ComponentModel.DataAnnotations; 3 | using System.ComponentModel.DataAnnotations.Schema; 4 | 5 | namespace EntityFrameworkCoreMock.Tests.Models 6 | { 7 | public class GeneratedGuidKeyModel 8 | { 9 | [Key, DatabaseGenerated(DatabaseGeneratedOption.Identity)] 10 | public Guid Id { get; set; } 11 | 12 | public string Value { get; set; } 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /tests/EntityFrameworkCoreMock.Moq.Tests/Models/GeneratedKeyModel.cs: -------------------------------------------------------------------------------- 1 | using System.ComponentModel.DataAnnotations; 2 | using System.ComponentModel.DataAnnotations.Schema; 3 | 4 | namespace EntityFrameworkCoreMock.Tests.Models 5 | { 6 | public class GeneratedKeyModel 7 | { 8 | [Key, DatabaseGenerated(DatabaseGeneratedOption.Identity)] 9 | public long Id { get; set; } 10 | 11 | public string Value { get; set; } 12 | } 13 | } 14 | -------------------------------------------------------------------------------- /tests/EntityFrameworkCoreMock.Moq.Tests/Models/Issue20Model.cs: -------------------------------------------------------------------------------- 1 | using System.ComponentModel.DataAnnotations; 2 | using System.ComponentModel.DataAnnotations.Schema; 3 | 4 | namespace EntityFrameworkCoreMock.Tests.Models 5 | { 6 | [Table("LoggingRepository")] 7 | public class Issue20Model 8 | { 9 | [Key, DatabaseGenerated(DatabaseGeneratedOption.Identity)] 10 | public int LoggingRepositoryId { get; set; } 11 | 12 | public string Url { get; set; } 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /tests/EntityFrameworkCoreMock.Moq.Tests/Models/NoKeyModel.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | 3 | namespace EntityFrameworkCoreMock.Tests.Models 4 | { 5 | public class NoKeyModel 6 | { 7 | public Guid ModelId { get; set; } 8 | 9 | public string Value { get; set; } 10 | } 11 | } 12 | -------------------------------------------------------------------------------- /tests/EntityFrameworkCoreMock.Moq.Tests/Models/Order.cs: -------------------------------------------------------------------------------- 1 | using System.ComponentModel.DataAnnotations; 2 | using System.ComponentModel.DataAnnotations.Schema; 3 | 4 | namespace EntityFrameworkCoreMock.Tests.Models 5 | { 6 | public class Order 7 | { 8 | [Key, DatabaseGenerated(DatabaseGeneratedOption.Identity)] 9 | public int Id { get; set; } 10 | 11 | public virtual User User { get; set; } 12 | } 13 | } 14 | -------------------------------------------------------------------------------- /tests/EntityFrameworkCoreMock.Moq.Tests/Models/PrivateSetterPropertyModel.cs: -------------------------------------------------------------------------------- 1 | namespace EntityFrameworkCoreMock.Tests.Models 2 | { 3 | public class PrivateSetterPropertyModel 4 | { 5 | private PrivateSetterPropertyModel() { } 6 | 7 | public PrivateSetterPropertyModel(string value) 8 | { 9 | Private = value; 10 | } 11 | 12 | public string Private { get; private set; } 13 | } 14 | } -------------------------------------------------------------------------------- /tests/EntityFrameworkCoreMock.Moq.Tests/Models/ProtectedSetterPropertyModel.cs: -------------------------------------------------------------------------------- 1 | namespace EntityFrameworkCoreMock.Tests.Models 2 | { 3 | public class ProtectedSetterPropertyModel 4 | { 5 | public string Protected { get; protected set; } 6 | } 7 | } -------------------------------------------------------------------------------- /tests/EntityFrameworkCoreMock.Moq.Tests/Models/User.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.ComponentModel.DataAnnotations; 3 | using System.ComponentModel.DataAnnotations.Schema; 4 | 5 | namespace EntityFrameworkCoreMock.Tests.Models 6 | { 7 | public class User 8 | { 9 | [Key, Column(Order = 0)] 10 | public Guid Id { get; set; } 11 | 12 | public string FullName { get; set; } 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /tests/EntityFrameworkCoreMock.NSubstitute.Tests/AutoMapperRelatedTests.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Linq; 3 | using System.Threading.Tasks; 4 | using AutoMapper; 5 | using AutoMapper.QueryableExtensions; 6 | using EntityFrameworkCoreMock.Tests.Models; 7 | using Microsoft.EntityFrameworkCore; 8 | using NUnit.Framework; 9 | 10 | namespace EntityFrameworkCoreMock.NSubstitute.Tests 11 | { 12 | [TestFixture] 13 | public class AutoMapperRelatedTests 14 | { 15 | public class UserModel 16 | { 17 | public string FullName { get; set; } 18 | 19 | public string Name { get; set; } 20 | } 21 | 22 | [Test] 23 | public async Task DbSetMock_AutoMapperProjectTo() 24 | { 25 | var mapperConfiguration = new MapperConfiguration(config => 26 | { 27 | config 28 | .CreateMap() 29 | .ForMember(d => d.Name, opt => opt.MapFrom(s => s.FullName)); 30 | }); 31 | 32 | var dbSetMock = new DbSetMock(new[] 33 | { 34 | new User { Id = Guid.NewGuid(), FullName = "Fake Drake" }, 35 | new User { Id = Guid.NewGuid(), FullName = "Jackira Spicy" } 36 | }, (x, _) => x.Id); 37 | var dbSet = dbSetMock.Object; 38 | 39 | Assert.That(await dbSet.CountAsync(), Is.EqualTo(2)); 40 | 41 | var models = await dbSet 42 | .Where(u => u.FullName != null) 43 | .ProjectTo(mapperConfiguration) 44 | .ToListAsync(); 45 | 46 | Assert.That(models.Count, Is.EqualTo(2)); 47 | } 48 | } 49 | } 50 | -------------------------------------------------------------------------------- /tests/EntityFrameworkCoreMock.NSubstitute.Tests/DbContextMockTests.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Threading; 5 | using System.Threading.Tasks; 6 | using EntityFrameworkCoreMock.Tests.Models; 7 | using Microsoft.EntityFrameworkCore; 8 | using NUnit.Framework; 9 | 10 | namespace EntityFrameworkCoreMock.NSubstitute.Tests 11 | { 12 | [TestFixture] 13 | public class DbContextMockTests 14 | { 15 | [Test] 16 | public void DbContextMock_Constructor_PassDbContextOptions_ShouldPassDbContextOptionsToMockedClass() 17 | { 18 | // Act 19 | var dbContextMock = new DbContextMock(Options); 20 | 21 | // Assert 22 | Assert.That(dbContextMock.Object.Options, Is.EqualTo(Options)); 23 | } 24 | 25 | [Test] 26 | public async Task DbContextMock_Constructor_ShouldSetupSaveChanges() 27 | { 28 | // Arrange 29 | var dbContextMock = new DbContextMock(Options); 30 | 31 | // Act 32 | dbContextMock.RegisterDbSetMock(x => x.Users, new TestDbSetMock()); 33 | 34 | // Assert 35 | Assert.That(dbContextMock.Object.SaveChanges(), Is.EqualTo(55861)); 36 | Assert.That(dbContextMock.Object.SaveChanges(true), Is.EqualTo(55861)); 37 | Assert.That(await dbContextMock.Object.SaveChangesAsync(), Is.EqualTo(55861)); 38 | Assert.That(await dbContextMock.Object.SaveChangesAsync(CancellationToken.None), Is.EqualTo(55861)); 39 | } 40 | 41 | [Test] 42 | public void DbContextMock_Reset_ShouldForgetMockedDbSets() 43 | { 44 | // Arrange 45 | var dbContextMock = new DbContextMock(Options); 46 | dbContextMock.RegisterDbSetMock(x => x.Users, new TestDbSetMock()); 47 | Assert.That(dbContextMock.Object.SaveChanges(), Is.EqualTo(55861)); 48 | 49 | // Act 50 | dbContextMock.Reset(); 51 | 52 | // Assert 53 | Assert.That(dbContextMock.Object.SaveChanges(), Is.EqualTo(0)); 54 | } 55 | 56 | [Test] 57 | public void DbContextMock_Reset_ShouldResetupSaveChanges() 58 | { 59 | // Arrange 60 | var dbContextMock = new DbContextMock(Options); 61 | dbContextMock.RegisterDbSetMock(x => x.Users, new TestDbSetMock()); 62 | Assert.That(dbContextMock.Object.SaveChanges(), Is.EqualTo(55861)); 63 | dbContextMock.Reset(); 64 | Assert.That(dbContextMock.Object.SaveChanges(), Is.EqualTo(0)); 65 | 66 | // Act 67 | dbContextMock.RegisterDbSetMock(x => x.Users, new TestDbSetMock()); 68 | 69 | // Assert 70 | Assert.That(dbContextMock.Object.SaveChanges(), Is.EqualTo(55861)); 71 | } 72 | 73 | [Test] 74 | public void DbContextMock_CreateDbSetMock_CreateIdenticalDbSetMockTwice_ShouldThrowExceptionSecondTime() 75 | { 76 | // Arrange 77 | var dbContextMock = new DbContextMock(Options); 78 | dbContextMock.CreateDbSetMock(x => x.Users); 79 | 80 | // Act 81 | void CreateDbMock() 82 | { 83 | dbContextMock.CreateDbSetMock(x => x.Users); 84 | } 85 | 86 | // Assert 87 | var ex = Assert.Throws(CreateDbMock); 88 | Assert.That(ex.ParamName, Is.EqualTo("dbSetSelector")); 89 | Assert.That(ex.Message, Does.StartWith("DbSetMock for entity User already created")); 90 | } 91 | 92 | [Test] 93 | public void DbContextMock_CreateDbSetMock_ShouldSetupMockForDbSetSelector() 94 | { 95 | var dbContextMock = new DbContextMock(Options); 96 | Assert.Throws(() => dbContextMock.Object.Users.ToArray()); 97 | dbContextMock.CreateDbSetMock(x => x.Users); 98 | Assert.That(dbContextMock.Object.Users, Is.Not.Null); 99 | } 100 | 101 | [Test] 102 | public async Task DbContextMock_CreateDbSetMock_PassInitialEntities_DbSetShouldContainInitialEntities() 103 | { 104 | // Arrange 105 | var dbContextMock = new DbContextMock(Options); 106 | 107 | // Act 108 | dbContextMock.CreateDbSetMock(x => x.Users, new[] 109 | { 110 | new User { Id = Guid.NewGuid(), FullName = "Eric Cartoon" }, 111 | new User { Id = Guid.NewGuid(), FullName = "Billy Jewel" }, 112 | }); 113 | 114 | // Assert 115 | Assert.That(dbContextMock.Object.Users.Count(), Is.EqualTo(2)); 116 | Assert.That(await dbContextMock.Object.Users.CountAsync(), Is.EqualTo(2)); 117 | 118 | var result = await dbContextMock.Object.Users.FirstAsync(x => x.FullName.StartsWith("Eric")); 119 | Assert.That(result.FullName, Is.EqualTo("Eric Cartoon")); 120 | 121 | result = dbContextMock.Object.Users.First(x => x.FullName.Contains("Jewel")); 122 | Assert.That(result.FullName, Is.EqualTo("Billy Jewel")); 123 | } 124 | 125 | [Test] 126 | public void DbContextMock_CreateDbSetMock_NoKeyFactoryForModelWithoutId_ShouldThrowException() 127 | { 128 | // Arrange 129 | var dbContextMock = new DbContextMock(Options); 130 | 131 | // Act & Assert 132 | var ex = Assert.Throws(() => dbContextMock.CreateDbSetMock(x => x.NoKeyModels)); 133 | Assert.That(ex.Message, Does.StartWith("No key factory could be created for entity type NoKeyModel, see inner exceptions")); 134 | } 135 | 136 | [Test] 137 | public void DbContextMock_CreateDbSetMock_PassCustomKeyFactoryForModelWithoutId_ShouldNotThrowException() 138 | { 139 | var dbContextMock = new DbContextMock(Options); 140 | Assert.DoesNotThrow(() => 141 | dbContextMock.CreateDbSetMock( 142 | x => x.NoKeyModels, (x, _) => x.ModelId)); 143 | } 144 | 145 | [Ignore("Not yet ported to EntityFrameworkCoreMock")] 146 | public void DbContextMock_CreateDbSetMock_AddModelWithSameKeyTwice_ShouldThrowDbUpdatedException() 147 | { 148 | // Arrange 149 | var userId = Guid.NewGuid(); 150 | var dbContextMock = new DbContextMock(Options); 151 | var dbSetMock = dbContextMock.CreateDbSetMock(x => x.Users); 152 | dbSetMock.Object.Add(new User { Id = userId, FullName = "SomeName" }); 153 | dbSetMock.Object.Add(new User { Id = Guid.NewGuid(), FullName = "SomeName" }); 154 | dbContextMock.Object.SaveChanges(); 155 | dbSetMock.Object.Add(new User { Id = userId, FullName = "SomeName" }); 156 | 157 | // Act 158 | void CallSaveChanges() 159 | { 160 | dbContextMock.Object.SaveChanges(); 161 | } 162 | 163 | // Assert 164 | Assert.Throws(CallSaveChanges); 165 | } 166 | 167 | [Ignore("Not yet ported to EntityFrameworkCoreMock")] 168 | public void DbContextMock_CreateDbSetMock_DeleteUnknownModel_ShouldThrowDbUpdateConcurrencyException() 169 | { 170 | var dbContextMock = new DbContextMock(Options); 171 | var dbSetMock = dbContextMock.CreateDbSetMock(x => x.Users); 172 | dbSetMock.Object.Remove(new User { Id = Guid.NewGuid() }); 173 | Assert.Throws(() => dbContextMock.Object.SaveChanges()); 174 | } 175 | 176 | [Test] 177 | public void DbContextMock_CreateDbSetMock_AddMultipleModelsWithDatabaseGeneratedIdentityKey_ShouldGenerateSequentialKey() 178 | { 179 | var dbContextMock = new DbContextMock(Options); 180 | var dbSetMock = dbContextMock.CreateDbSetMock(x => x.GeneratedKeyModels, new[] 181 | { 182 | new GeneratedKeyModel {Value = "first"}, 183 | new GeneratedKeyModel {Value = "second"} 184 | }); 185 | dbSetMock.Object.Add(new GeneratedKeyModel { Value = "third" }); 186 | dbContextMock.Object.SaveChanges(); 187 | 188 | Assert.That(dbSetMock.Object.Min(x => x.Id), Is.EqualTo(1)); 189 | Assert.That(dbSetMock.Object.Max(x => x.Id), Is.EqualTo(3)); 190 | Assert.That(dbSetMock.Object.First(x => x.Id == 1).Value, Is.EqualTo("first")); 191 | Assert.That(dbSetMock.Object.First(x => x.Id == 2).Value, Is.EqualTo("second")); 192 | Assert.That(dbSetMock.Object.First(x => x.Id == 3).Value, Is.EqualTo("third")); 193 | } 194 | 195 | [Test] 196 | public void DbContextMock_CreateDbSetMock_AddMultipleModelsWithGuidAsDatabaseGeneratedIdentityKey_ShouldGenerateRandomGuidAsKey() 197 | { 198 | var knownId = Guid.NewGuid(); 199 | var dbContextMock = new DbContextMock(Options); 200 | var dbSetMock = dbContextMock.CreateDbSetMock(x => x.GeneratedGuidKeyModels, new[] 201 | { 202 | new GeneratedGuidKeyModel {Id = knownId, Value = "first"}, 203 | new GeneratedGuidKeyModel {Value = "second"} 204 | }); 205 | dbSetMock.Object.Add(new GeneratedGuidKeyModel { Value = "third" }); 206 | dbContextMock.Object.SaveChanges(); 207 | 208 | var modelWithKnownId = dbSetMock.Object.FirstOrDefault(x => x.Id == knownId); 209 | Assert.That(modelWithKnownId, Is.Not.Null); 210 | Assert.That(modelWithKnownId.Value, Is.EqualTo("first")); 211 | } 212 | 213 | [Test] 214 | public async Task DbContextMock_CreateDbSetMock_AsyncAddMultipleModelsWithLongAsDatabaseGeneratedIdentityKey_ShouldGenerateIncrementalKey() 215 | { 216 | // Arrange 217 | var dbContextMock = new DbContextMock(Options); 218 | var dbSetMock = dbContextMock.CreateDbSetMock(x => x.Issue20Models); 219 | 220 | // Act 221 | await dbContextMock.Object.Issue20Models.AddAsync(new Issue20Model { Url = "A" }); 222 | await dbContextMock.Object.Issue20Models.AddAsync(new Issue20Model { Url = "B" }); 223 | await dbContextMock.Object.Issue20Models.AddAsync(new Issue20Model { Url = "C" }); 224 | await dbContextMock.Object.SaveChangesAsync(); 225 | 226 | // Assert 227 | Assert.That(dbSetMock.Object.First(x => x.Url == "A").LoggingRepositoryId, Is.EqualTo(1)); 228 | Assert.That(dbSetMock.Object.First(x => x.Url == "B").LoggingRepositoryId, Is.EqualTo(2)); 229 | Assert.That(dbSetMock.Object.First(x => x.Url == "C").LoggingRepositoryId, Is.EqualTo(3)); 230 | } 231 | 232 | [Test] 233 | public void DbContextMock_MultipleGets_ShouldReturnDataEachTime() 234 | { 235 | // Arrange 236 | var users = new List() 237 | { 238 | new User() { Id = Guid.NewGuid(), FullName = "Ian Kilmister" }, 239 | new User() { Id = Guid.NewGuid(), FullName = "Phil Taylor" }, 240 | new User() { Id = Guid.NewGuid(), FullName = "Eddie Clarke" } 241 | }; 242 | 243 | var dbContextMock = new DbContextMock(Options); 244 | dbContextMock.CreateDbSetMock(x => x.Users, users); 245 | 246 | List results = new List(); 247 | 248 | // Act 249 | for (int i = 1; i <= 100; i++) 250 | { 251 | var readUsers = dbContextMock.Object.Users; 252 | foreach (var user in readUsers) 253 | { 254 | results.Add(user.FullName); 255 | } 256 | } 257 | 258 | // Assert 259 | Assert.AreEqual(300, results.Count()); 260 | foreach (var result in results) 261 | { 262 | Assert.IsNotEmpty(result); 263 | } 264 | } 265 | 266 | [Test] 267 | public void DbContextMock_CreateDbSetMock_GenericDbSetSelector_ShouldReturnDbSetMock() 268 | { 269 | var dbContextMock = new DbContextMock(Options); 270 | var dbSetMock = dbContextMock.CreateDbSetMock(x => x.Set()); 271 | Assert.That(dbSetMock.Object, Is.Not.Null); 272 | } 273 | 274 | [Test] 275 | public void DbContextMock_GenericSet_ShouldReturnDbSetMock() 276 | { 277 | var dbContextMock = new DbContextMock(Options); 278 | var dbSetMock = dbContextMock.CreateDbSetMock(x => x.Users); 279 | var dbSet = dbContextMock.Object.Set(); 280 | Assert.That(dbSet, Is.Not.Null); 281 | Assert.That(dbSet, Is.EqualTo(dbSetMock.Object)); 282 | } 283 | 284 | [Test] 285 | public void DbContextMock_BeginTransaction_CommitTransaction_ShouldNotFail() 286 | { 287 | var dbContextMock = new DbContextMock(Options); 288 | Assert.DoesNotThrow(() => 289 | { 290 | var transaction = dbContextMock.Object.Database.BeginTransaction(); 291 | transaction.Commit(); 292 | transaction.Rollback(); 293 | }); 294 | 295 | Assert.DoesNotThrowAsync(async () => 296 | { 297 | var transaction = await dbContextMock.Object.Database.BeginTransactionAsync(); 298 | await transaction.CommitAsync(); 299 | await transaction.RollbackAsync(); 300 | }); 301 | } 302 | 303 | [Test] 304 | public void DbContextMock_Add_ShouldAddEntity() 305 | { 306 | var dbContextMock = new DbContextMock(Options); 307 | var user = new User { Id = Guid.NewGuid(), FullName = "Mark Kramer" }; 308 | dbContextMock.CreateDbSetMock(x => x.Users, Array.Empty()); 309 | 310 | dbContextMock.Object.Add(user); 311 | dbContextMock.Object.SaveChanges(); 312 | 313 | var dbSet = dbContextMock.Object.Users; 314 | Assert.That(dbSet.Count(), Is.EqualTo(1)); 315 | var actualUser = dbSet.First(); 316 | Assert.That(actualUser, Is.Not.Null); 317 | Assert.That(actualUser.FullName, Is.EqualTo("Mark Kramer")); 318 | } 319 | 320 | [Test] 321 | public async Task DbContextMock_AddAsync_ShouldAddEntity() 322 | { 323 | var dbContextMock = new DbContextMock(Options); 324 | var user = new User { Id = Guid.NewGuid(), FullName = "Mark Kramer" }; 325 | dbContextMock.CreateDbSetMock(x => x.Users, Array.Empty()); 326 | 327 | await dbContextMock.Object.AddAsync(user); 328 | await dbContextMock.Object.SaveChangesAsync(); 329 | 330 | var dbSet = dbContextMock.Object.Users; 331 | Assert.That(dbSet.Count(), Is.EqualTo(1)); 332 | var actualUser = dbSet.First(); 333 | Assert.That(actualUser, Is.Not.Null); 334 | Assert.That(actualUser.FullName, Is.EqualTo("Mark Kramer")); 335 | } 336 | 337 | [Test] 338 | public void DbContextMock_Update_ShouldUpdateEntity() 339 | { 340 | var dbContextMock = new DbContextMock(Options); 341 | var user = new User { Id = Guid.NewGuid(), FullName = "Mark Kramer" }; 342 | dbContextMock.CreateDbSetMock(x => x.Users, new[] { user }); 343 | 344 | dbContextMock.Object.Update(new User { Id = user.Id, FullName = "Updated name" }); 345 | dbContextMock.Object.SaveChanges(); 346 | 347 | var dbSet = dbContextMock.Object.Users; 348 | Assert.That(dbSet.Count(), Is.EqualTo(1)); 349 | var actualUser = dbSet.First(); 350 | Assert.That(actualUser, Is.Not.Null); 351 | Assert.That(actualUser.FullName, Is.EqualTo("Updated name")); 352 | } 353 | 354 | [Test] 355 | public void DbContextMock_Remove_ShouldRemoveEntity() 356 | { 357 | var dbContextMock = new DbContextMock(Options); 358 | var user = new User { Id = Guid.NewGuid(), FullName = "Mark Kramer" }; 359 | dbContextMock.CreateDbSetMock(x => x.Users, new[] { user }); 360 | 361 | dbContextMock.Object.Remove(user); 362 | dbContextMock.Object.SaveChanges(); 363 | 364 | var dbSet = dbContextMock.Object.Users; 365 | Assert.That(dbSet.Count(), Is.EqualTo(0)); 366 | } 367 | 368 | public class TestDbSetMock : IDbSetMock 369 | { 370 | public int SaveChanges() => 55861; 371 | } 372 | 373 | public DbContextOptions Options { get; } = new DbContextOptionsBuilder().Options; 374 | 375 | public class TestDbContext : DbContext 376 | { 377 | public TestDbContext(DbContextOptions options) 378 | : base(options) 379 | { 380 | Options = options; 381 | } 382 | 383 | public DbContextOptions Options { get; } 384 | 385 | public virtual DbSet Users { get; set; } 386 | 387 | public virtual DbSet NoKeyModels { get; set; } 388 | 389 | public virtual DbSet GeneratedKeyModels { get; set; } 390 | 391 | public virtual DbSet GeneratedGuidKeyModels { get; set; } 392 | 393 | public virtual DbSet Issue20Models { get; set; } 394 | } 395 | } 396 | } 397 | -------------------------------------------------------------------------------- /tests/EntityFrameworkCoreMock.NSubstitute.Tests/DbSetMockTests.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.ComponentModel.DataAnnotations.Schema; 4 | using System.Linq; 5 | using System.Threading.Tasks; 6 | using EntityFrameworkCoreMock.Tests.Models; 7 | using Microsoft.EntityFrameworkCore; 8 | using NUnit.Framework; 9 | 10 | namespace EntityFrameworkCoreMock.NSubstitute.Tests 11 | { 12 | [TestFixture] 13 | public class DbSetMockTests 14 | { 15 | 16 | [Test] 17 | public void DbSetMock_AsNoTracking_ShouldBeMocked() 18 | { 19 | var dbSetMock = new DbSetMock(null, (x, _) => x.Id); 20 | var dbSet = dbSetMock.Object; 21 | Assert.That(dbSet.AsNoTracking(), Is.EqualTo(dbSet)); 22 | } 23 | 24 | [Test] 25 | public void DbSetMock_Include_ShouldBeMocked() 26 | { 27 | var dbSetMock = new DbSetMock(null, (x, _) => x.Id); 28 | var dbSet = dbSetMock.Object; 29 | Assert.That(dbSet.Include(x => x.User), Is.EqualTo(dbSet)); 30 | } 31 | 32 | [Test] 33 | public void DbSetMock_GivenEntityIsAdded_ShouldAddAfterCallingSaveChanges() 34 | { 35 | var user = new User { Id = Guid.NewGuid(), FullName = "Fake Drake" }; 36 | var dbSetMock = new DbSetMock(null, (x, _) => x.Id); 37 | var dbSet = dbSetMock.Object; 38 | 39 | Assert.That(dbSet.Count(), Is.EqualTo(0)); 40 | dbSet.Add(user); 41 | Assert.That(dbSet.Count(), Is.EqualTo(0)); 42 | ((IDbSetMock)dbSetMock).SaveChanges(); 43 | Assert.That(dbSet.Count(), Is.EqualTo(1)); 44 | Assert.That(dbSet.Any(x => x.Id == user.Id && x.FullName == user.FullName), Is.True); 45 | } 46 | 47 | [Test] 48 | public void DbSetMock_GivenEntityRangeIsAdded_ShouldAddAfterCallingSaveChanges() 49 | { 50 | // Arrange 51 | var users = new[] 52 | { 53 | new User { Id = Guid.NewGuid(), FullName = "Ian Kilmister" }, 54 | new User { Id = Guid.NewGuid(), FullName = "Phil Taylor" }, 55 | new User { Id = Guid.NewGuid(), FullName = "Eddie Clarke" } 56 | }; 57 | var dbSetMock = new DbSetMock(null, (x, _) => x.Id); 58 | var dbSet = dbSetMock.Object; 59 | 60 | Assert.That(dbSet.Count(), Is.EqualTo(0)); 61 | 62 | // Act 63 | dbSet.AddRange(users); 64 | ((IDbSetMock)dbSetMock).SaveChanges(); 65 | 66 | // Assert 67 | var firstUser = users.First(); 68 | Assert.That(dbSet.Count(), Is.EqualTo(3)); 69 | Assert.That(dbSet.Any(x => x.Id == firstUser.Id 70 | && x.FullName == firstUser.FullName), Is.True); 71 | } 72 | 73 | [Test] 74 | public void DbSetMock_GivenEntityIsUpdated_ShouldUpdateAfterCallingSaveChanges() 75 | { 76 | var user = new User { Id = Guid.NewGuid(), FullName = "Fake Drake" }; 77 | var dbSetMock = new DbSetMock(new[] { user }, (x, _) => x.Id); 78 | var dbSet = dbSetMock.Object; 79 | 80 | dbSet.Update(new User { Id = user.Id, FullName = "Fake Snake" }); 81 | Assert.That(dbSet.First().FullName, Is.EqualTo("Fake Drake")); 82 | ((IDbSetMock)dbSetMock).SaveChanges(); 83 | Assert.That(dbSet.Count(), Is.EqualTo(1)); 84 | Assert.That(dbSet.First().FullName, Is.EqualTo("Fake Snake")); 85 | } 86 | 87 | [Test] 88 | public void DbSetMock_GivenEntityRangeIsUpdated_ShouldUpdateAfterCallingSaveChanges() 89 | { 90 | // Arrange 91 | var users = new[] 92 | { 93 | new User { Id = Guid.NewGuid(), FullName = "Ian Kilmister" }, 94 | new User { Id = Guid.NewGuid(), FullName = "Phil Taylor" }, 95 | new User { Id = Guid.NewGuid(), FullName = "Eddie Clarke" } 96 | }; 97 | var dbSetMock = new DbSetMock(users, (x, _) => x.Id); 98 | var dbSet = dbSetMock.Object; 99 | 100 | // Act 101 | dbSet.UpdateRange(new[] 102 | { 103 | new User { Id = users[0].Id, FullName = "Ian Kilmister AAA" }, 104 | new User { Id = users[1].Id, FullName = "Phil Taylor AAA" }, 105 | new User { Id = users[2].Id, FullName = "Eddie Clarke AAA" } 106 | }); 107 | ((IDbSetMock)dbSetMock).SaveChanges(); 108 | 109 | // Assert 110 | Assert.That(dbSet.Count(), Is.EqualTo(3)); 111 | Assert.That(dbSet.All(x => x.FullName.EndsWith("AAA")), Is.True); 112 | } 113 | 114 | [Test] 115 | public async Task DbSetMock_AsyncProvider() 116 | { 117 | var user = new User { Id = Guid.NewGuid(), FullName = "Fake Drake" }; 118 | var dbSetMock = new DbSetMock(null, (x, _) => x.Id); 119 | var dbSet = dbSetMock.Object; 120 | 121 | Assert.That(await dbSet.CountAsync(), Is.EqualTo(0)); 122 | dbSet.Add(user); 123 | Assert.That(await dbSet.CountAsync(), Is.EqualTo(0)); 124 | ((IDbSetMock)dbSetMock).SaveChanges(); 125 | Assert.That(await dbSet.CountAsync(), Is.EqualTo(1)); 126 | Assert.That(await dbSet.AnyAsync(x => x.Id == user.Id && x.FullName == user.FullName), Is.True); 127 | } 128 | 129 | [Test] 130 | public void DbSetMock_GivenEntityIsRemoved_ShouldRemoveAfterCallingSaveChanges() 131 | { 132 | var user = new User { Id = Guid.NewGuid(), FullName = "Fake Drake" }; 133 | var dbSetMock = new DbSetMock(new[] 134 | { 135 | user, 136 | new User {Id = Guid.NewGuid(), FullName = "Jackira Spicy"} 137 | }, (x, _) => x.Id); 138 | var dbSet = dbSetMock.Object; 139 | 140 | Assert.That(dbSet.Count(), Is.EqualTo(2)); 141 | dbSet.Remove(new User { Id = user.Id }); 142 | Assert.That(dbSet.Count(), Is.EqualTo(2)); 143 | Assert.That(dbSet.Any(x => x.Id == user.Id && x.FullName == user.FullName), Is.True); 144 | ((IDbSetMock)dbSetMock).SaveChanges(); 145 | Assert.That(dbSet.Count(), Is.EqualTo(1)); 146 | Assert.That(dbSet.Any(x => x.Id == user.Id && x.FullName == user.FullName), Is.False); 147 | } 148 | 149 | [Test] 150 | public void DbSetMock_GivenRangeOfEntitiesIsRemoved_ShouldRemoveAfterCallingSaveChanges() 151 | { 152 | var users = new[] 153 | { 154 | new User {Id = Guid.NewGuid(), FullName = "User 1"}, 155 | new User {Id = Guid.NewGuid(), FullName = "User 2"}, 156 | new User {Id = Guid.NewGuid(), FullName = "User 3"} 157 | }; 158 | var dbSetMock = new DbSetMock(users, (x, _) => x.Id); 159 | var dbSet = dbSetMock.Object; 160 | 161 | Assert.That(dbSet.Count(), Is.EqualTo(3)); 162 | dbSet.RemoveRange(users.Skip(1)); 163 | Assert.That(dbSet.Count(), Is.EqualTo(3)); 164 | ((IDbSetMock)dbSetMock).SaveChanges(); 165 | Assert.That(dbSet.Count(), Is.EqualTo(1)); 166 | Assert.That(dbSet.Any(x => x.FullName == "User 1"), Is.True); 167 | Assert.That(dbSet.Any(x => x.FullName == "User 2"), Is.False); 168 | } 169 | 170 | [Test] 171 | public void DbSetMock_SaveChanges_GivenEntityPropertyIsChanged_ShouldFireSavedChangesEventWithCorrectUpdatedInfo() 172 | { 173 | var userId = Guid.NewGuid(); 174 | var dbSetMock = new DbSetMock(new[] 175 | { 176 | new User {Id = userId, FullName = "Mark Kramer"}, 177 | new User {Id = Guid.NewGuid(), FullName = "Freddy Kipcurry"} 178 | }, (x, _) => x.Id); 179 | var dbSet = dbSetMock.Object; 180 | 181 | Assert.That(dbSet.Count(), Is.EqualTo(2)); 182 | var fetchedUser = dbSet.First(x => x.Id == userId); 183 | fetchedUser.FullName = "Kramer Mark"; 184 | 185 | SavedChangesEventArgs eventArgs = null; 186 | dbSetMock.SavedChanges += (sender, args) => eventArgs = args; 187 | 188 | ((IDbSetMock)dbSetMock).SaveChanges(); 189 | 190 | Assert.That(eventArgs, Is.Not.Null); 191 | Assert.That(eventArgs.UpdatedEntities, Has.Length.EqualTo(1)); 192 | var updatedEntity = eventArgs.UpdatedEntities[0]; 193 | Assert.That(updatedEntity.UpdatedProperties, Has.Length.EqualTo(1)); 194 | var updatedProperty = updatedEntity.UpdatedProperties[0]; 195 | Assert.That(updatedProperty.Name, Is.EqualTo("FullName")); 196 | Assert.That(updatedProperty.Original, Is.EqualTo("Mark Kramer")); 197 | Assert.That(updatedProperty.New, Is.EqualTo("Kramer Mark")); 198 | } 199 | 200 | [Test] 201 | public void DbSetMock_SaveChanges_GivenEntityPropertyMarkedAsNotMapped_ShouldNotMarkNotMappedPropertyAsModified() 202 | { 203 | var dbSetMock = new DbSetMock(new[] 204 | { 205 | new NestedModel {Id = Guid.NewGuid(), NestedDocument = new NestedModel.Document()}, 206 | new NestedModel {Id = Guid.NewGuid(), NestedDocument = new NestedModel.Document()}, 207 | new NestedModel {Id = Guid.NewGuid(), NestedDocument = new NestedModel.Document()} 208 | }, (x, _) => x.Id); 209 | 210 | SavedChangesEventArgs eventArgs = null; 211 | dbSetMock.SavedChanges += (sender, args) => eventArgs = args; 212 | 213 | dbSetMock.Object.First().Value = "abc"; 214 | 215 | ((IDbSetMock)dbSetMock).SaveChanges(); 216 | 217 | Assert.That(eventArgs, Is.Not.Null); 218 | Assert.That(eventArgs.UpdatedEntities, Has.Length.EqualTo(1)); 219 | Assert.That(eventArgs.UpdatedEntities.First().UpdatedProperties, Has.Length.EqualTo(1)); 220 | var updatedProperty = eventArgs.UpdatedEntities.First().UpdatedProperties.First(); 221 | Assert.That(updatedProperty.Name, Is.EqualTo("Value")); 222 | Assert.That(updatedProperty.Original, Is.EqualTo(null)); 223 | Assert.That(updatedProperty.New, Is.EqualTo("abc")); 224 | } 225 | 226 | [Test] 227 | public void DbSetMock_Empty_AsEnumerable_ShouldReturnEmptyEnumerable() 228 | { 229 | var dbSetMock = new DbSetMock(new List(), (x, _) => x.Id); 230 | var nestedModels = dbSetMock.Object.AsEnumerable(); 231 | Assert.That(nestedModels, Is.Not.Null); 232 | Assert.That(nestedModels, Is.Empty); 233 | } 234 | 235 | [Test] 236 | public void DbSetMock_AsEnumerable_ShouldReturnEnumerableCollection() 237 | { 238 | var dbSetMock = new DbSetMock(new[] 239 | { 240 | new NestedModel {Id = Guid.NewGuid(), NestedDocument = new NestedModel.Document()}, 241 | new NestedModel {Id = Guid.NewGuid(), NestedDocument = new NestedModel.Document()} 242 | }, (x, _) => x.Id); 243 | var nestedModels = dbSetMock.Object.AsEnumerable(); 244 | Assert.That(nestedModels, Is.Not.Null); 245 | Assert.That(nestedModels.Count(), Is.EqualTo(2)); 246 | } 247 | 248 | [Test] 249 | public async Task DbSetMock_AsyncProvider_ShouldReturnRequestedModel() 250 | { 251 | var userId = Guid.NewGuid(); 252 | var dbSetMock = new DbSetMock(new[] 253 | { 254 | new User {Id = userId, FullName = "Mark Kramer"}, 255 | new User {Id = Guid.NewGuid(), FullName = "Freddy Kipcurry"} 256 | }, (x, _) => x.Id); 257 | 258 | var model = await dbSetMock.Object.Where(x => x.Id == userId).FirstOrDefaultAsync(); 259 | Assert.That(model, Is.Not.Null); 260 | Assert.That(model.FullName, Is.EqualTo("Mark Kramer")); 261 | } 262 | 263 | [Test] 264 | public async Task DbSetMock_AsyncProvider_OrderBy_ShouldReturnRequestedModel() 265 | { 266 | var dbSetMock = new DbSetMock(new[] 267 | { 268 | new User {Id = Guid.NewGuid(), FullName = "Mark Kramer"}, 269 | new User {Id = Guid.NewGuid(), FullName = "Freddy Kipcurry"} 270 | }, (x, _) => x.Id); 271 | 272 | var result = await dbSetMock.Object.Where(x => x.Id != Guid.Empty).OrderBy(x => x.FullName).ToListAsync(); 273 | Assert.That(result, Is.Not.Null); 274 | Assert.That(result, Has.Count.EqualTo(2)); 275 | Assert.That(result.First().FullName, Is.EqualTo("Freddy Kipcurry")); 276 | } 277 | 278 | [Test] 279 | public void DbSetMock_Find_ShouldReturnRequestedModel() 280 | { 281 | Guid user1 = Guid.NewGuid(), user2 = Guid.NewGuid(); 282 | var dbSetMock = new DbSetMock(new[] 283 | { 284 | new User {Id = user1, FullName = "Mark Kramer"}, 285 | new User {Id = user2, FullName = "Freddy Kipcurry"} 286 | }, (x, _) => x.Id); 287 | 288 | var result = dbSetMock.Object.Find(user2); 289 | Assert.That(result, Is.Not.Null); 290 | Assert.That(result.FullName, Is.EqualTo("Freddy Kipcurry")); 291 | } 292 | 293 | [Test] 294 | public void DbSetMock_Find_UnknownId_ShouldReturnNull() 295 | { 296 | var unknownUser = Guid.NewGuid(); 297 | var dbSetMock = new DbSetMock(new[] 298 | { 299 | new User {Id = Guid.NewGuid(), FullName = "Mark Kramer"}, 300 | new User {Id = Guid.NewGuid(), FullName = "Freddy Kipcurry"} 301 | }, (x, _) => x.Id); 302 | 303 | var result = dbSetMock.Object.Find(unknownUser); 304 | Assert.That(result, Is.Null); 305 | } 306 | 307 | [Test] 308 | public void DbSetMock_FindOnCompositeTupleKey_ShouldReturnRequestedModel() 309 | { 310 | Guid modelId1 = Guid.NewGuid(), modelId2 = Guid.NewGuid(); 311 | var dbSetMock = new DbSetMock(new[] 312 | { 313 | new NoKeyModel {ModelId = modelId1, Value = "Value 1"}, 314 | new NoKeyModel {ModelId = modelId2, Value = "Value 2"} 315 | }, (x, _) => new Tuple(x.ModelId, x.Value)); 316 | 317 | var result = dbSetMock.Object.Find(modelId2, "Value 2"); 318 | Assert.That(result, Is.Not.Null); 319 | Assert.That(result.ModelId, Is.EqualTo(modelId2)); 320 | Assert.That(result.Value, Is.EqualTo("Value 2")); 321 | } 322 | 323 | [Test] 324 | public void DbSetMock_FindOnCompositeValueTupleKey_ShouldReturnRequestedModel() 325 | { 326 | Guid modelId1 = Guid.NewGuid(), modelId2 = Guid.NewGuid(); 327 | var dbSetMock = new DbSetMock(new[] 328 | { 329 | new NoKeyModel {ModelId = modelId1, Value = "Value 1"}, 330 | new NoKeyModel {ModelId = modelId2, Value = "Value 2"} 331 | }, (x, _) => (x.ModelId, x.Value)); 332 | 333 | var result = dbSetMock.Object.Find(modelId2, "Value 2"); 334 | Assert.That(result, Is.Not.Null); 335 | Assert.That(result.ModelId, Is.EqualTo(modelId2)); 336 | Assert.That(result.Value, Is.EqualTo("Value 2")); 337 | } 338 | 339 | public class NestedModel 340 | { 341 | public Guid Id { get; set; } 342 | 343 | public string Value { get; set; } 344 | 345 | [NotMapped] 346 | public Document NestedDocument 347 | { 348 | get { return new Document { Name = Guid.NewGuid().ToString("N") }; } 349 | // ReSharper disable once ValueParameterNotUsed 350 | set { } 351 | } 352 | 353 | public class Document 354 | { 355 | public string Name { get; set; } 356 | } 357 | } 358 | 359 | [Test] 360 | public void DbSetMock_SaveChanges_GivenAbstractEntityModel_ShouldNotThrowException() 361 | { 362 | var dbSetMock = new DbSetMock(new[] 363 | { 364 | new ConcreteModel {Id = Guid.NewGuid()} 365 | }, (x, _) => x.Id); 366 | 367 | ((IDbSetMock)dbSetMock).SaveChanges(); 368 | } 369 | 370 | public abstract class AbstractModel 371 | { 372 | public Guid Id { get; set; } 373 | } 374 | 375 | public class ConcreteModel : AbstractModel 376 | { 377 | public string Name { get; set; } = "SomeName"; 378 | } 379 | 380 | [Test] 381 | public void DbSetMock_ModelPropertyWithPrivateSetter_ShouldSetTheProperty() 382 | { 383 | var dbSetMock = new DbSetMock(new[] 384 | { 385 | new PrivateSetterPropertyModel("my value") 386 | }, (x, _) => x.Private); 387 | 388 | var dbSet = dbSetMock.Object; 389 | Assert.That(dbSet.First().Private, Is.EqualTo("my value")); 390 | } 391 | } 392 | } 393 | -------------------------------------------------------------------------------- /tests/EntityFrameworkCoreMock.NSubstitute.Tests/EntityFrameworkCoreMock.NSubstitute.Tests.csproj: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | -------------------------------------------------------------------------------- /tests/EntityFrameworkCoreMock.NSubstitute.Tests/Models/GeneratedGuidKeyModel.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.ComponentModel.DataAnnotations; 3 | using System.ComponentModel.DataAnnotations.Schema; 4 | 5 | namespace EntityFrameworkCoreMock.Tests.Models 6 | { 7 | public class GeneratedGuidKeyModel 8 | { 9 | [Key, DatabaseGenerated(DatabaseGeneratedOption.Identity)] 10 | public Guid Id { get; set; } 11 | 12 | public string Value { get; set; } 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /tests/EntityFrameworkCoreMock.NSubstitute.Tests/Models/GeneratedKeyModel.cs: -------------------------------------------------------------------------------- 1 | using System.ComponentModel.DataAnnotations; 2 | using System.ComponentModel.DataAnnotations.Schema; 3 | 4 | namespace EntityFrameworkCoreMock.Tests.Models 5 | { 6 | public class GeneratedKeyModel 7 | { 8 | [Key, DatabaseGenerated(DatabaseGeneratedOption.Identity)] 9 | public long Id { get; set; } 10 | 11 | public string Value { get; set; } 12 | } 13 | } 14 | -------------------------------------------------------------------------------- /tests/EntityFrameworkCoreMock.NSubstitute.Tests/Models/Issue20Model.cs: -------------------------------------------------------------------------------- 1 | using System.ComponentModel.DataAnnotations; 2 | using System.ComponentModel.DataAnnotations.Schema; 3 | 4 | namespace EntityFrameworkCoreMock.Tests.Models 5 | { 6 | [Table("LoggingRepository")] 7 | public class Issue20Model 8 | { 9 | [Key, DatabaseGenerated(DatabaseGeneratedOption.Identity)] 10 | public int LoggingRepositoryId { get; set; } 11 | 12 | public string Url { get; set; } 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /tests/EntityFrameworkCoreMock.NSubstitute.Tests/Models/NoKeyModel.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | 3 | namespace EntityFrameworkCoreMock.Tests.Models 4 | { 5 | public class NoKeyModel 6 | { 7 | public Guid ModelId { get; set; } 8 | 9 | public string Value { get; set; } 10 | } 11 | } 12 | -------------------------------------------------------------------------------- /tests/EntityFrameworkCoreMock.NSubstitute.Tests/Models/Order.cs: -------------------------------------------------------------------------------- 1 | using System.ComponentModel.DataAnnotations; 2 | using System.ComponentModel.DataAnnotations.Schema; 3 | 4 | namespace EntityFrameworkCoreMock.Tests.Models 5 | { 6 | public class Order 7 | { 8 | [Key, DatabaseGenerated(DatabaseGeneratedOption.Identity)] 9 | public int Id { get; set; } 10 | 11 | public virtual User User { get; set; } 12 | } 13 | } 14 | -------------------------------------------------------------------------------- /tests/EntityFrameworkCoreMock.NSubstitute.Tests/Models/PrivateSetterPropertyModel.cs: -------------------------------------------------------------------------------- 1 | namespace EntityFrameworkCoreMock.Tests.Models 2 | { 3 | public class PrivateSetterPropertyModel 4 | { 5 | private PrivateSetterPropertyModel() { } 6 | 7 | public PrivateSetterPropertyModel(string value) 8 | { 9 | Private = value; 10 | } 11 | 12 | public string Private { get; private set; } 13 | } 14 | } -------------------------------------------------------------------------------- /tests/EntityFrameworkCoreMock.NSubstitute.Tests/Models/User.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.ComponentModel.DataAnnotations; 3 | using System.ComponentModel.DataAnnotations.Schema; 4 | 5 | namespace EntityFrameworkCoreMock.Tests.Models 6 | { 7 | public class User 8 | { 9 | [Key, Column(Order = 0)] 10 | public Guid Id { get; set; } 11 | 12 | public string FullName { get; set; } 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /tests/EntityFrameworkCoreMock.Shared.Tests/EntityFrameworkCoreMock.Shared.Tests.csproj: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | -------------------------------------------------------------------------------- /tests/EntityFrameworkCoreMock.Shared.Tests/KeyContextTests.cs: -------------------------------------------------------------------------------- 1 | using NUnit.Framework; 2 | 3 | namespace EntityFrameworkCoreMock.Shared.Tests 4 | { 5 | [TestFixture] 6 | public class KeyContextTests 7 | { 8 | [Test] 9 | public void NextIdentity_FirstCall_ShouldReturnOne() 10 | { 11 | var keyContext = new KeyContext(); 12 | Assert.That(keyContext.NextIdentity, Is.EqualTo(1)); 13 | } 14 | 15 | [Test] 16 | public void NextIdentity_CallTenTimes_ShouldIncrementEachCall() 17 | { 18 | var keyContext = new KeyContext(); 19 | for (var i = 1; i <= 10; i++) 20 | { 21 | Assert.That(keyContext.NextIdentity, Is.EqualTo(i)); 22 | } 23 | } 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /tests/EntityFrameworkCoreMock.Shared.Tests/KeyFactoryBuilders/AttributeBasedKeyFactoryBuilderTests.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.ComponentModel.DataAnnotations; 3 | using EntityFrameworkCoreMock.Shared.Tests.Models; 4 | using NUnit.Framework; 5 | 6 | namespace EntityFrameworkCoreMock.Shared.Tests.KeyFactoryBuilders 7 | { 8 | [TestFixture] 9 | public class AttributeBasedKeyFactoryBuilderTests 10 | { 11 | [Test] 12 | public void AttributeBasedKeyFactoryBuilder_GivenModelWithOneKeyProperty_ShouldReturnCorrectKey() 13 | { 14 | var builder = new AttributeBasedKeyFactoryBuilder(); 15 | var factory = builder.BuildKeyFactory(); 16 | var userId = Guid.NewGuid(); 17 | var key = factory(new UserWithKeyAttribute { UserId = userId, FullName = "Jake Snake" }, null); 18 | Assert.That(key, Is.EqualTo(new Tuple(userId))); 19 | } 20 | 21 | [Test] 22 | public void AttributeBasedKeyFactoryBuilder_GivenModelWithTwoKeyProperties_ShouldReturnCorrectKey() 23 | { 24 | var builder = new AttributeBasedKeyFactoryBuilder(); 25 | var factory = builder.BuildKeyFactory(); 26 | var userId = Guid.NewGuid(); 27 | var tenant = Guid.NewGuid().ToString("N"); 28 | var key = factory(new UserWithAdditionalKeyAttribute { UserId = userId, Tenant = tenant, FullName = "Jake Snake" }, null); 29 | Assert.That(key, Is 30 | .EqualTo(new Tuple(userId, tenant)) 31 | .Or 32 | .EqualTo(new Tuple(tenant, userId))); 33 | } 34 | 35 | [Test] 36 | public void AttributeBasedKeyFactoryBuilder_GivenModelWithoutKeyProperties_ShouldThrowException() 37 | { 38 | var builder = new AttributeBasedKeyFactoryBuilder(); 39 | var exception = Assert.Throws(() => builder.BuildKeyFactory()); 40 | Assert.That(exception.Message, Is.EqualTo("Entity type UserWithoutKeyAttribute does not contain any property marked with KeyAttribute")); 41 | } 42 | } 43 | } 44 | -------------------------------------------------------------------------------- /tests/EntityFrameworkCoreMock.Shared.Tests/KeyFactoryBuilders/ConventionBasedKeyFactoryBuilderTests.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using EntityFrameworkCoreMock.Shared.Tests.Models; 3 | using NUnit.Framework; 4 | 5 | namespace EntityFrameworkCoreMock.Shared.Tests.KeyFactoryBuilders 6 | { 7 | [TestFixture] 8 | public class ConventionBasedKeyFactoryBuilderTests 9 | { 10 | [Test] 11 | public void ConventionBasedKeyFactoryBuilder_GivenModelWithIdProperty_ShouldReturnCorrectKey() 12 | { 13 | // Arrange 14 | var builder = new ConventionBasedKeyFactoryBuilder(); 15 | var factory = builder.BuildKeyFactory(); 16 | var id = Guid.NewGuid(); 17 | 18 | // Act 19 | var key = factory(new UserWithIdProperty { Id = id, FullName = "Jake Snake" }, null); 20 | 21 | // Assert 22 | Assert.That(key, Is.EqualTo(new Tuple(id))); 23 | } 24 | 25 | [Test] 26 | public void ConventionBasedKeyFactoryBuilder_GivenModelWithClassPrefixedIdProperty_ShouldReturnCorrectKey() 27 | { 28 | // Arrange 29 | var builder = new ConventionBasedKeyFactoryBuilder(); 30 | var factory = builder.BuildKeyFactory(); 31 | var id = Guid.NewGuid(); 32 | 33 | // Act 34 | var key = factory(new UserWithKeyByConvention { UserWithKeyByConventionId = id, FullName = "Jake Snake" }, null); 35 | 36 | // Assert 37 | Assert.That(key, Is.EqualTo(new Tuple(id))); 38 | } 39 | 40 | [Test] 41 | public void ConventionBasedKeyFactoryBuilder_GivenModelWithMultipleConventionBasedIdProperties_ShouldThrowException() 42 | { 43 | // Arrange 44 | var builder = new ConventionBasedKeyFactoryBuilder(); 45 | 46 | // Act & Assert 47 | var exception = Assert.Throws(() => builder.BuildKeyFactory()); 48 | Assert.That(exception.Message, Is.EqualTo("Entity type UserWithMultipleKeysByConvention contains multiple conventional id properties")); 49 | } 50 | 51 | [Test] 52 | public void ConventionBasedKeyFactoryBuilder_GivenModelWithoutIdProperty_ShouldThrowException() 53 | { 54 | // Arrange 55 | var builder = new ConventionBasedKeyFactoryBuilder(); 56 | 57 | // Act & Assert 58 | var exception = Assert.Throws(() => builder.BuildKeyFactory()); 59 | Assert.That(exception.Message, Is.EqualTo("Entity type UserWithoutKeyByConvention does not contain any property named Id or UserWithoutKeyByConventionId")); 60 | } 61 | } 62 | } 63 | -------------------------------------------------------------------------------- /tests/EntityFrameworkCoreMock.Shared.Tests/Models/UserWithAdditionalKeyAttribute.cs: -------------------------------------------------------------------------------- 1 | using System.ComponentModel.DataAnnotations; 2 | using System.ComponentModel.DataAnnotations.Schema; 3 | 4 | namespace EntityFrameworkCoreMock.Shared.Tests.Models 5 | { 6 | public class UserWithAdditionalKeyAttribute : UserWithKeyAttribute 7 | { 8 | [Key, Column(Order = 1), MaxLength(50)] 9 | public string Tenant { get; set; } 10 | } 11 | } 12 | -------------------------------------------------------------------------------- /tests/EntityFrameworkCoreMock.Shared.Tests/Models/UserWithIdProperty.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | 3 | namespace EntityFrameworkCoreMock.Shared.Tests.Models 4 | { 5 | public class UserWithIdProperty 6 | { 7 | public Guid Id { get; set; } 8 | 9 | public string FullName { get; set; } 10 | } 11 | } 12 | -------------------------------------------------------------------------------- /tests/EntityFrameworkCoreMock.Shared.Tests/Models/UserWithKeyAttribute.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.ComponentModel.DataAnnotations; 3 | using System.ComponentModel.DataAnnotations.Schema; 4 | 5 | namespace EntityFrameworkCoreMock.Shared.Tests.Models 6 | { 7 | public class UserWithKeyAttribute 8 | { 9 | [Key, Column(Order = 0)] 10 | public Guid UserId { get; set; } 11 | 12 | public string FullName { get; set; } 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /tests/EntityFrameworkCoreMock.Shared.Tests/Models/UserWithKeyByConvention.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | 3 | namespace EntityFrameworkCoreMock.Shared.Tests.Models 4 | { 5 | public class UserWithKeyByConvention 6 | { 7 | public Guid UserWithKeyByConventionId { get; set; } 8 | 9 | public string FullName { get; set; } 10 | } 11 | } 12 | -------------------------------------------------------------------------------- /tests/EntityFrameworkCoreMock.Shared.Tests/Models/UserWithMultipleKeysByConvention.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | 3 | namespace EntityFrameworkCoreMock.Shared.Tests.Models 4 | { 5 | public class UserWithMultipleKeysByConvention 6 | { 7 | public Guid Id { get; set; } 8 | 9 | public Guid UserWithMultipleKeysByConventionId { get; set; } 10 | 11 | public string FullName { get; set; } 12 | } 13 | } 14 | -------------------------------------------------------------------------------- /tests/EntityFrameworkCoreMock.Shared.Tests/Models/UserWithoutKeyAttribute.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.ComponentModel.DataAnnotations; 3 | using System.ComponentModel.DataAnnotations.Schema; 4 | 5 | namespace EntityFrameworkCoreMock.Shared.Tests.Models 6 | { 7 | public class UserWithoutKeyAttribute 8 | { 9 | public Guid UserId { get; set; } 10 | 11 | public string FullName { get; set; } 12 | } 13 | } 14 | -------------------------------------------------------------------------------- /tests/EntityFrameworkCoreMock.Shared.Tests/Models/UserWithoutKeyByConvention.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | 3 | namespace EntityFrameworkCoreMock.Shared.Tests.Models 4 | { 5 | public class UserWithoutKeyByConvention 6 | { 7 | public Guid UserId { get; set; } 8 | 9 | public string FullName { get; set; } 10 | } 11 | } 12 | --------------------------------------------------------------------------------