Repository: rgvlee/EntityFrameworkCore.Testing
Branch: 10.x
Commit: 648c8656557b
Files: 122
Total size: 400.2 KB
Directory structure:
gitextract_5vjkh0op/
├── .github/
│ └── workflows/
│ ├── continuous-integration-checks.yml
│ └── release.yml
├── .gitignore
├── EntityFrameworkCore.Testing.Moq.nuspec
├── EntityFrameworkCore.Testing.NSubstitute.nuspec
├── EntityFrameworkCore.Testing.sln
├── LICENSE
├── README.md
├── TODO.md
├── googlea6bd68d4a55b1e59.html
└── src/
├── EntityFrameworkCore.DefaultBehaviour.Tests/
│ ├── ByTypeDbSetTests.cs
│ ├── ByTypeReadOnlyDbSetExceptionTests.cs
│ ├── ByTypeReadOnlyDbSetTests.cs
│ ├── DbContextTests.cs
│ ├── EntityFrameworkCore.DefaultBehaviour.Tests.csproj
│ ├── Issue114Tests.cs
│ ├── Issue117Tests.cs
│ ├── Issue49Tests.cs
│ └── Issue88Tests.cs
├── EntityFrameworkCore.Testing.Common/
│ ├── AsyncEnumerable.cs
│ ├── AsyncEnumerator.cs
│ ├── AsyncQueryProvider.cs
│ ├── EntityFrameworkCore.Testing.Common.csproj
│ ├── EntityFrameworkCore.Testing.Common.xml
│ ├── ExceptionMessages.Designer.cs
│ ├── ExceptionMessages.resx
│ ├── Helpers/
│ │ ├── BaseMockedDbContextBuilder.cs
│ │ ├── BaseMockedDbContextFactory.cs
│ │ ├── ExpressionHelper.cs
│ │ ├── IMockedDbContextBuilder.cs
│ │ ├── MockedDbContextFactoryOptions.cs
│ │ └── ParameterMatchingHelper.cs
│ └── QueryRootExpression.cs
├── EntityFrameworkCore.Testing.Common.Tests/
│ ├── AsyncEnumerableTests.cs
│ ├── BaseForDbContextTests.cs
│ ├── BaseForDbSetTests.cs
│ ├── BaseForMockedQueryableTests.cs
│ ├── BaseForQueryableTests.cs
│ ├── BaseForReadOnlyDbSetTests.cs
│ ├── BaseForTests.cs
│ ├── BaseTestEntity.cs
│ ├── EntityFrameworkCore.Testing.Common.Tests.csproj
│ ├── Issue114Tests.cs
│ ├── Issue117Tests.cs
│ ├── Issue126Tests.cs
│ ├── Issue49Tests.cs
│ ├── Issue88Tests.cs
│ ├── MappingProfile.cs
│ ├── NotRegisteredEntity.cs
│ ├── ReadOnlyDbSetExceptionTests.cs
│ ├── TestDbContext.cs
│ ├── TestEntity.cs
│ ├── TestReadOnlyEntity.cs
│ └── TestViewModel.cs
├── EntityFrameworkCore.Testing.Moq/
│ ├── Create.cs
│ ├── EntityFrameworkCore.Testing.Moq.csproj
│ ├── EntityFrameworkCore.Testing.Moq.xml
│ ├── Extensions/
│ │ ├── DbContextExtensions.cs
│ │ ├── DbSetExtensions.Internal.cs
│ │ ├── QueryProviderExtensions.Internal.cs
│ │ ├── QueryProviderExtensions.cs
│ │ ├── QueryableExtensions.cs
│ │ ├── ReadOnlyDbSetExtensions.Internal.cs
│ │ └── ReadOnlyDbSetExtensions.cs
│ └── Helpers/
│ ├── MockedDbContextBuilder.cs
│ ├── MockedDbContextFactory.Internal.cs
│ └── NoSetUpDefaultValueProvider.cs
├── EntityFrameworkCore.Testing.Moq.Tests/
│ ├── BaseForDbContextTests.cs
│ ├── BaseForDbQueryTests.cs
│ ├── BaseForDbSetTests.cs
│ ├── ByPropertyDbSetTests.cs
│ ├── ByPropertyReadOnlyDbSetExceptionTests.cs
│ ├── ByPropertyReadOnlyDbSetTests.cs
│ ├── ByTypeDbSetTests.cs
│ ├── ByTypeReadOnlyDbSetExceptionTests.cs
│ ├── ByTypeReadOnlyDbSetTests.cs
│ ├── CreateFactoryTests.cs
│ ├── DbContextTestsUsingConstructorParameters.cs
│ ├── DbContextTestsUsingType.cs
│ ├── EntityFrameworkCore.Testing.Moq.Tests.csproj
│ ├── Issue114Tests.cs
│ ├── Issue117Tests.cs
│ ├── Issue126Tests.cs
│ ├── Issue1Tests.cs
│ ├── Issue49Tests.cs
│ ├── Issue4Tests.cs
│ ├── Issue6Tests.cs
│ └── Issue88Tests.cs
├── EntityFrameworkCore.Testing.NSubstitute/
│ ├── Create.cs
│ ├── EntityFrameworkCore.Testing.NSubstitute.csproj
│ ├── EntityFrameworkCore.Testing.NSubstitute.xml
│ ├── Extensions/
│ │ ├── DbContextExtensions.cs
│ │ ├── DbSetExtensions.Internal.cs
│ │ ├── QueryProviderExtensions.Internal.cs
│ │ ├── QueryProviderExtensions.cs
│ │ ├── QueryableExtensions.cs
│ │ ├── ReadOnlyDbSetExtensions.Internal.cs
│ │ └── ReadOnlyDbSetExtensions.cs
│ └── Helpers/
│ ├── MockedDbContextBuilder.cs
│ ├── MockedDbContextFactory.Internal.cs
│ └── NoSetUpHandler.cs
└── EntityFrameworkCore.Testing.NSubstitute.Tests/
├── BaseForDbContextTests.cs
├── BaseForDbQueryTests.cs
├── BaseForDbSetTests.cs
├── ByPropertyDbSetTests.cs
├── ByPropertyReadOnlyDbSetExceptionTests.cs
├── ByPropertyReadOnlyDbSetTests.cs
├── ByTypeDbSetTests.cs
├── ByTypeReadOnlyDbSetExceptionTests.cs
├── ByTypeReadOnlyDbSetTests.cs
├── CreateFactoryTests.cs
├── DbContextTestsUsingConstructorParameters.cs
├── DbContextTestsUsingType.cs
├── EntityFrameworkCore.Testing.NSubstitute.Tests.csproj
├── Issue114Tests.cs
├── Issue117Tests.cs
├── Issue126Tests.cs
├── Issue1Tests.cs
├── Issue49Tests.cs
├── Issue4Tests.cs
├── Issue6Tests.cs
└── Issue88Tests.cs
================================================
FILE CONTENTS
================================================
================================================
FILE: .github/workflows/continuous-integration-checks.yml
================================================
name: Continuous Integration Checks
on:
push:
schedule:
- cron: "0 9 * * 3"
jobs:
build-and-test:
name: Build and test
runs-on: ubuntu-latest
steps:
- name: Checkout
uses: actions/checkout@v5
- name: Setup dotnet
uses: actions/setup-dotnet@v5
with:
dotnet-version: 10.0.x
- name: Build
run: dotnet build --configuration Release
# - name: List dependencies
# run: dotnet list EntityFrameworkCore.Testing.sln package
- name: Test
run: dotnet test --configuration Release --no-build /p:CollectCoverage=\"true\" /p:Exclude=\"[*.Tests]*,[rgvlee.Core.*]*\" /p:SkipAutoProps=\"false\" /p:IncludeTestAssembly=\"false\" /p:CoverletOutput=\"../../CoverageResults/\" /p:MergeWith=\"../../CoverageResults/coverage.json\" /p:CoverletOutputFormat=\"opencover,json\" -m:1
- name: Update dependencies
run: |
dotnet add src/EntityFrameworkCore.Testing.Common package Microsoft.EntityFrameworkCore.InMemory --version 10.*-*
dotnet add src/EntityFrameworkCore.Testing.Common package Microsoft.EntityFrameworkCore.Relational --version 10.*-*
dotnet add src/EntityFrameworkCore.Testing.Common package Microsoft.Extensions.Logging --version 10.*-*
dotnet add src/EntityFrameworkCore.Testing.Common package rgvlee.Core
dotnet add src/EntityFrameworkCore.Testing.Common.Tests package Microsoft.Extensions.Logging.Console --version 10.*-*
dotnet add src/EntityFrameworkCore.Testing.Moq package Moq
dotnet add src/EntityFrameworkCore.Testing.NSubstitute package NSubstitute
# - name: List dependencies
# run: dotnet list EntityFrameworkCore.Testing.sln package
- name: Test with updated dependencies
run: dotnet test --configuration Release /p:CollectCoverage=\"false\" /p:Exclude=\"[*.Tests]*,[rgvlee.Core.*]*\" /p:SkipAutoProps=\"false\" /p:IncludeTestAssembly=\"false\" -m:1
- name: Send coverage results to Codacy
uses: codacy/codacy-coverage-reporter-action@master
with:
project-token: ${{ secrets.CODACY_PROJECT_TOKEN }}
coverage-reports: ./CoverageResults/coverage.*opencover.xml
================================================
FILE: .github/workflows/release.yml
================================================
name: Release
on:
release:
types: [published]
jobs:
build-and-test:
name: Build, pack and push
runs-on: ubuntu-latest
steps:
- name: Checkout
uses: actions/checkout@v5
- name: Setup dotnet
uses: actions/setup-dotnet@v5
with:
dotnet-version: 10.0.x
- run: sudo apt install mono-devel
- name: Setup NuGet
uses: nuget/setup-nuget@v2
with:
nuget-version: latest
- name: Build
run: dotnet build --configuration Release
- name: Pack
run: |
nuget pack EntityFrameworkCore.Testing.Moq.nuspec -Version ${{ github.event.release.name }} -Symbols -SymbolPackageFormat snupkg
nuget pack EntityFrameworkCore.Testing.NSubstitute.nuspec -Version ${{ github.event.release.name }} -Symbols -SymbolPackageFormat snupkg
- name: Push
run: |
nuget push EntityFrameworkCore.Testing.Moq*.nupkg -Source https://api.nuget.org/v3/index.json -ApiKey ${{ secrets.NUGET_API_KEY }}
nuget push EntityFrameworkCore.Testing.NSubstitute*.nupkg -Source https://api.nuget.org/v3/index.json -ApiKey ${{ secrets.NUGET_API_KEY }}
================================================
FILE: .gitignore
================================================
## Ignore Visual Studio temporary files, build results, and
## files generated by popular Visual Studio add-ons.
##
## Get latest from https://github.com/github/gitignore/blob/master/VisualStudio.gitignore
# User-specific files
*.suo
*.user
*.userosscache
*.sln.docstates
# User-specific files (MonoDevelop/Xamarin Studio)
*.userprefs
# Build results
[Dd]ebug/
[Dd]ebugPublic/
[Rr]elease/
[Rr]eleases/
x64/
x86/
bld/
[Bb]in/
[Oo]bj/
[Ll]og/
# Visual Studio 2015/2017 cache/options directory
.vs/
# Uncomment if you have tasks that create the project's static files in wwwroot
#wwwroot/
# Visual Studio 2017 auto generated files
Generated\ Files/
# MSTest test Results
[Tt]est[Rr]esult*/
[Bb]uild[Ll]og.*
# NUNIT
*.VisualState.xml
TestResult.xml
# Build Results of an ATL Project
[Dd]ebugPS/
[Rr]eleasePS/
dlldata.c
# Benchmark Results
BenchmarkDotNet.Artifacts/
# .NET Core
project.lock.json
project.fragment.lock.json
artifacts/
**/Properties/launchSettings.json
# StyleCop
StyleCopReport.xml
# Files built by Visual Studio
*_i.c
*_p.c
*_i.h
*.ilk
*.meta
*.obj
*.iobj
*.pch
*.pdb
*.ipdb
*.pgc
*.pgd
*.rsp
*.sbr
*.tlb
*.tli
*.tlh
*.tmp
*.tmp_proj
*.log
*.vspscc
*.vssscc
.builds
*.pidb
*.svclog
*.scc
# Chutzpah Test files
_Chutzpah*
# Visual C++ cache files
ipch/
*.aps
*.ncb
*.opendb
*.opensdf
*.sdf
*.cachefile
*.VC.db
*.VC.VC.opendb
# Visual Studio profiler
*.psess
*.vsp
*.vspx
*.sap
# Visual Studio Trace Files
*.e2e
# TFS 2012 Local Workspace
$tf/
# Guidance Automation Toolkit
*.gpState
# ReSharper is a .NET coding add-in
_ReSharper*/
*.[Rr]e[Ss]harper
*.DotSettings.user
# JustCode is a .NET coding add-in
.JustCode
# TeamCity is a build add-in
_TeamCity*
# DotCover is a Code Coverage Tool
*.dotCover
# AxoCover is a Code Coverage Tool
.axoCover/*
!.axoCover/settings.json
# Visual Studio code coverage results
*.coverage
*.coveragexml
# NCrunch
_NCrunch_*
.*crunch*.local.xml
nCrunchTemp_*
# MightyMoose
*.mm.*
AutoTest.Net/
# Web workbench (sass)
.sass-cache/
# Installshield output folder
[Ee]xpress/
# DocProject is a documentation generator add-in
DocProject/buildhelp/
DocProject/Help/*.HxT
DocProject/Help/*.HxC
DocProject/Help/*.hhc
DocProject/Help/*.hhk
DocProject/Help/*.hhp
DocProject/Help/Html2
DocProject/Help/html
# Click-Once directory
publish/
# Publish Web Output
*.[Pp]ublish.xml
*.azurePubxml
# Note: Comment the next line if you want to checkin your web deploy settings,
# but database connection strings (with potential passwords) will be unencrypted
*.pubxml
*.publishproj
# Microsoft Azure Web App publish settings. Comment the next line if you want to
# checkin your Azure Web App publish settings, but sensitive information contained
# in these scripts will be unencrypted
PublishScripts/
# NuGet Packages
*.nupkg
# The packages folder can be ignored because of Package Restore
**/[Pp]ackages/*
# except build/, which is used as an MSBuild target.
!**/[Pp]ackages/build/
# Uncomment if necessary however generally it will be regenerated when needed
#!**/[Pp]ackages/repositories.config
# NuGet v3's project.json files produces more ignorable files
*.nuget.props
*.nuget.targets
# Microsoft Azure Build Output
csx/
*.build.csdef
# Microsoft Azure Emulator
ecf/
rcf/
# Windows Store app package directories and files
AppPackages/
BundleArtifacts/
Package.StoreAssociation.xml
_pkginfo.txt
*.appx
# Visual Studio cache files
# files ending in .cache can be ignored
*.[Cc]ache
# but keep track of directories ending in .cache
!*.[Cc]ache/
# Others
ClientBin/
~$*
*~
*.dbmdl
*.dbproj.schemaview
*.jfm
*.pfx
*.publishsettings
orleans.codegen.cs
# Including strong name files can present a security risk
# (https://github.com/github/gitignore/pull/2483#issue-259490424)
#*.snk
# Since there are multiple workflows, uncomment next line to ignore bower_components
# (https://github.com/github/gitignore/pull/1529#issuecomment-104372622)
#bower_components/
# RIA/Silverlight projects
Generated_Code/
# Backup & report files from converting an old project file
# to a newer Visual Studio version. Backup files are not needed,
# because we have git ;-)
_UpgradeReport_Files/
Backup*/
UpgradeLog*.XML
UpgradeLog*.htm
ServiceFabricBackup/
*.rptproj.bak
# SQL Server files
*.mdf
*.ldf
*.ndf
# Business Intelligence projects
*.rdl.data
*.bim.layout
*.bim_*.settings
*.rptproj.rsuser
# Microsoft Fakes
FakesAssemblies/
# GhostDoc plugin setting file
*.GhostDoc.xml
# Node.js Tools for Visual Studio
.ntvs_analysis.dat
node_modules/
# Visual Studio 6 build log
*.plg
# Visual Studio 6 workspace options file
*.opt
# Visual Studio 6 auto-generated workspace file (contains which files were open etc.)
*.vbw
# Visual Studio LightSwitch build output
**/*.HTMLClient/GeneratedArtifacts
**/*.DesktopClient/GeneratedArtifacts
**/*.DesktopClient/ModelManifest.xml
**/*.Server/GeneratedArtifacts
**/*.Server/ModelManifest.xml
_Pvt_Extensions
# Paket dependency manager
.paket/paket.exe
paket-files/
# FAKE - F# Make
.fake/
# JetBrains Rider
.idea/
*.sln.iml
# CodeRush
.cr/
# Python Tools for Visual Studio (PTVS)
__pycache__/
*.pyc
# Cake - Uncomment if you are using it
# tools/**
# !tools/packages.config
# Tabs Studio
*.tss
# Telerik's JustMock configuration file
*.jmconfig
# BizTalk build output
*.btp.cs
*.btm.cs
*.odx.cs
*.xsd.cs
# OpenCover UI analysis results
OpenCover/
# Azure Stream Analytics local run output
ASALocalRun/
# MSBuild Binary and Structured Log
*.binlog
# NVidia Nsight GPU debugger configuration file
*.nvuser
# MFractors (Xamarin productivity tool) working folder
.mfractor/
================================================
FILE: EntityFrameworkCore.Testing.Moq.nuspec
================================================
EntityFrameworkCore.Testing.Moq10.0.0rgvleergvleefalseLICENSEhttps://github.com/rgvlee/EntityFrameworkCore.TestingAdds relational support to the Microsoft EntityFrameworkCore in-memory database provider by mocking relational operations.
EntityFrameworkCore.Testing v1.x = EntityFrameworkCore 2 (2.1.0+)
EntityFrameworkCore.Testing v2.x = EntityFrameworkCore 3
EntityFrameworkCore.Testing v3.x = EntityFrameworkCore 5
EntityFrameworkCore.Testing v4.x = EntityFrameworkCore 6
EntityFrameworkCore.Testing v5.x = EntityFrameworkCore 7
EntityFrameworkCore.Testing v8.x = EntityFrameworkCore 8
EntityFrameworkCore.Testing v9.x = EntityFrameworkCore 9
EntityFrameworkCore.Testing v10.x = EntityFrameworkCore 10Copyright (c) 2025 Lee AndersonEntityFrameworkCore EFCore Moq mock testing
================================================
FILE: EntityFrameworkCore.Testing.NSubstitute.nuspec
================================================
EntityFrameworkCore.Testing.NSubstitute10.0.0rgvleergvleefalseLICENSEhttps://github.com/rgvlee/EntityFrameworkCore.TestingAdds relational support to the Microsoft EntityFrameworkCore in-memory database provider by mocking relational operations.
EntityFrameworkCore.Testing v1.x = EntityFrameworkCore 2 (2.1.0+)
EntityFrameworkCore.Testing v2.x = EntityFrameworkCore 3
EntityFrameworkCore.Testing v3.x = EntityFrameworkCore 5
EntityFrameworkCore.Testing v4.x = EntityFrameworkCore 6
EntityFrameworkCore.Testing v5.x = EntityFrameworkCore 7
EntityFrameworkCore.Testing v8.x = EntityFrameworkCore 8
EntityFrameworkCore.Testing v9.x = EntityFrameworkCore 9
EntityFrameworkCore.Testing v10.x = EntityFrameworkCore 10Copyright (c) 2025 Lee AndersonEntityFrameworkCore EFCore NSubstitute nsub mock testing
================================================
FILE: EntityFrameworkCore.Testing.sln
================================================
Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio Version 17
VisualStudioVersion = 17.3.32811.315
MinimumVisualStudioVersion = 10.0.40219.1
Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Solution Items", "Solution Items", "{F7DF11CE-7549-4808-B9BE-66CE1BD1F150}"
ProjectSection(SolutionItems) = preProject
.gitignore = .gitignore
.github\workflows\continuous-integration-checks.yml = .github\workflows\continuous-integration-checks.yml
src\EntityFrameworkCore.Testing.Common\EntityFrameworkCore.Testing.Common.xml = src\EntityFrameworkCore.Testing.Common\EntityFrameworkCore.Testing.Common.xml
EntityFrameworkCore.Testing.Moq.nuspec = EntityFrameworkCore.Testing.Moq.nuspec
src\EntityFrameworkCore.Testing.Moq\EntityFrameworkCore.Testing.Moq.xml = src\EntityFrameworkCore.Testing.Moq\EntityFrameworkCore.Testing.Moq.xml
EntityFrameworkCore.Testing.NSubstitute.nuspec = EntityFrameworkCore.Testing.NSubstitute.nuspec
src\EntityFrameworkCore.Testing.NSubstitute\EntityFrameworkCore.Testing.NSubstitute.xml = src\EntityFrameworkCore.Testing.NSubstitute\EntityFrameworkCore.Testing.NSubstitute.xml
googlea6bd68d4a55b1e59.html = googlea6bd68d4a55b1e59.html
LICENSE = LICENSE
README.md = README.md
.github\workflows\release.yml = .github\workflows\release.yml
TODO.md = TODO.md
EndProjectSection
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "EntityFrameworkCore.Testing.Moq", "src\EntityFrameworkCore.Testing.Moq\EntityFrameworkCore.Testing.Moq.csproj", "{3A00A558-6614-4D2C-8BC0-A74EFBB8F844}"
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "EntityFrameworkCore.Testing.Moq.Tests", "src\EntityFrameworkCore.Testing.Moq.Tests\EntityFrameworkCore.Testing.Moq.Tests.csproj", "{6567AA47-8E4D-4E69-8075-B8C25DC7F4A4}"
EndProject
Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Tests", "Tests", "{5B717CD0-96CD-4862-95EB-80ECCDCD1D07}"
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "EntityFrameworkCore.Testing.Common", "src\EntityFrameworkCore.Testing.Common\EntityFrameworkCore.Testing.Common.csproj", "{F2211544-E6EA-439A-9C31-3972B48B9D5E}"
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "EntityFrameworkCore.Testing.Common.Tests", "src\EntityFrameworkCore.Testing.Common.Tests\EntityFrameworkCore.Testing.Common.Tests.csproj", "{4B97C16B-E27D-4900-A535-6D5AC116B893}"
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "EntityFrameworkCore.DefaultBehaviour.Tests", "src\EntityFrameworkCore.DefaultBehaviour.Tests\EntityFrameworkCore.DefaultBehaviour.Tests.csproj", "{9C08E46C-C902-473F-93E6-FCB89DEC8C97}"
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "EntityFrameworkCore.Testing.NSubstitute", "src\EntityFrameworkCore.Testing.NSubstitute\EntityFrameworkCore.Testing.NSubstitute.csproj", "{A70976F0-38EA-461C-9BDE-BEE8232B048D}"
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "EntityFrameworkCore.Testing.NSubstitute.Tests", "src\EntityFrameworkCore.Testing.NSubstitute.Tests\EntityFrameworkCore.Testing.NSubstitute.Tests.csproj", "{2F67273D-B7B8-49A5-9A91-E37CBC10F563}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
Release|Any CPU = Release|Any CPU
EndGlobalSection
GlobalSection(ProjectConfigurationPlatforms) = postSolution
{3A00A558-6614-4D2C-8BC0-A74EFBB8F844}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{3A00A558-6614-4D2C-8BC0-A74EFBB8F844}.Debug|Any CPU.Build.0 = Debug|Any CPU
{3A00A558-6614-4D2C-8BC0-A74EFBB8F844}.Release|Any CPU.ActiveCfg = Release|Any CPU
{3A00A558-6614-4D2C-8BC0-A74EFBB8F844}.Release|Any CPU.Build.0 = Release|Any CPU
{6567AA47-8E4D-4E69-8075-B8C25DC7F4A4}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{6567AA47-8E4D-4E69-8075-B8C25DC7F4A4}.Debug|Any CPU.Build.0 = Debug|Any CPU
{6567AA47-8E4D-4E69-8075-B8C25DC7F4A4}.Release|Any CPU.ActiveCfg = Release|Any CPU
{6567AA47-8E4D-4E69-8075-B8C25DC7F4A4}.Release|Any CPU.Build.0 = Release|Any CPU
{F2211544-E6EA-439A-9C31-3972B48B9D5E}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{F2211544-E6EA-439A-9C31-3972B48B9D5E}.Debug|Any CPU.Build.0 = Debug|Any CPU
{F2211544-E6EA-439A-9C31-3972B48B9D5E}.Release|Any CPU.ActiveCfg = Release|Any CPU
{F2211544-E6EA-439A-9C31-3972B48B9D5E}.Release|Any CPU.Build.0 = Release|Any CPU
{4B97C16B-E27D-4900-A535-6D5AC116B893}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{4B97C16B-E27D-4900-A535-6D5AC116B893}.Debug|Any CPU.Build.0 = Debug|Any CPU
{4B97C16B-E27D-4900-A535-6D5AC116B893}.Release|Any CPU.ActiveCfg = Release|Any CPU
{4B97C16B-E27D-4900-A535-6D5AC116B893}.Release|Any CPU.Build.0 = Release|Any CPU
{9C08E46C-C902-473F-93E6-FCB89DEC8C97}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{9C08E46C-C902-473F-93E6-FCB89DEC8C97}.Debug|Any CPU.Build.0 = Debug|Any CPU
{9C08E46C-C902-473F-93E6-FCB89DEC8C97}.Release|Any CPU.ActiveCfg = Release|Any CPU
{9C08E46C-C902-473F-93E6-FCB89DEC8C97}.Release|Any CPU.Build.0 = Release|Any CPU
{A70976F0-38EA-461C-9BDE-BEE8232B048D}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{A70976F0-38EA-461C-9BDE-BEE8232B048D}.Debug|Any CPU.Build.0 = Debug|Any CPU
{A70976F0-38EA-461C-9BDE-BEE8232B048D}.Release|Any CPU.ActiveCfg = Release|Any CPU
{A70976F0-38EA-461C-9BDE-BEE8232B048D}.Release|Any CPU.Build.0 = Release|Any CPU
{2F67273D-B7B8-49A5-9A91-E37CBC10F563}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{2F67273D-B7B8-49A5-9A91-E37CBC10F563}.Debug|Any CPU.Build.0 = Debug|Any CPU
{2F67273D-B7B8-49A5-9A91-E37CBC10F563}.Release|Any CPU.ActiveCfg = Release|Any CPU
{2F67273D-B7B8-49A5-9A91-E37CBC10F563}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
EndGlobalSection
GlobalSection(NestedProjects) = preSolution
{6567AA47-8E4D-4E69-8075-B8C25DC7F4A4} = {5B717CD0-96CD-4862-95EB-80ECCDCD1D07}
{4B97C16B-E27D-4900-A535-6D5AC116B893} = {5B717CD0-96CD-4862-95EB-80ECCDCD1D07}
{9C08E46C-C902-473F-93E6-FCB89DEC8C97} = {5B717CD0-96CD-4862-95EB-80ECCDCD1D07}
{2F67273D-B7B8-49A5-9A91-E37CBC10F563} = {5B717CD0-96CD-4862-95EB-80ECCDCD1D07}
EndGlobalSection
GlobalSection(ExtensibilityGlobals) = postSolution
SolutionGuid = {0E585345-42EF-438B-8212-2C328D36D9AD}
EndGlobalSection
EndGlobal
================================================
FILE: LICENSE
================================================
MIT License
Copyright (c) 2025 Lee Anderson
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
================================================
FILE: README.md
================================================
# EntityFrameworkCore.Testing
[](https://www.codacy.com/manual/rgvlee/EntityFrameworkCore.Testing?utm_source=github.com&utm_medium=referral&utm_content=rgvlee/EntityFrameworkCore.Testing&utm_campaign=Badge_Grade) [](https://www.codacy.com/manual/rgvlee/EntityFrameworkCore.Testing?utm_source=github.com&utm_medium=referral&utm_content=rgvlee/EntityFrameworkCore.Testing&utm_campaign=Badge_Coverage)
## Overview
EntityFrameworkCore.Testing adds relational support to the Microsoft EntityFrameworkCore in-memory database provider by mocking relational operations. It's easy to use (usually just a single line of code) with implementations for both Moq and NSubstitute.
The aim of this library is to allow you use the in-memory database provider in unit tests where the SUT invokes a relational operation. It'll allow you to specify expected results for these relational operations. It does not test your relational operations.
[Microsoft does not recommend mocking a db context](https://docs.microsoft.com/en-us/ef/core/testing/#unit-testing) and EntityFrameworkCore.Testing follows this advice by sending operations supported by the in-memory database provider to the in-memory database provider.
### EntityFrameworkCore 10
- [Source](https://github.com/rgvlee/EntityFrameworkCore.Testing/tree/10.x)
- [EntityFrameworkCore.Testing.Moq - NuGet](https://www.nuget.org/packages/EntityFrameworkCore.Testing.Moq/10.0.0)
- [EntityFrameworkCore.Testing.NSubstitute - NuGet](https://www.nuget.org/packages/EntityFrameworkCore.Testing.NSubstitute/10.0.0)
### EntityFrameworkCore 9
- [Source](https://github.com/rgvlee/EntityFrameworkCore.Testing/tree/9.x)
- [EntityFrameworkCore.Testing.Moq - NuGet](https://www.nuget.org/packages/EntityFrameworkCore.Testing.Moq/9.0.2)
- [EntityFrameworkCore.Testing.NSubstitute - NuGet](https://www.nuget.org/packages/EntityFrameworkCore.Testing.NSubstitute/9.0.2)
### EntityFrameworkCore 8
- [Source](https://github.com/rgvlee/EntityFrameworkCore.Testing/tree/8.x)
- [EntityFrameworkCore.Testing.Moq - NuGet](https://www.nuget.org/packages/EntityFrameworkCore.Testing.Moq/8.1.2)
- [EntityFrameworkCore.Testing.NSubstitute - NuGet](https://www.nuget.org/packages/EntityFrameworkCore.Testing.NSubstitute/8.1.2)
### EntityFrameworkCore 7
- [Source](https://github.com/rgvlee/EntityFrameworkCore.Testing/tree/5.x)
- [EntityFrameworkCore.Testing.Moq - NuGet](https://www.nuget.org/packages/EntityFrameworkCore.Testing.Moq/5.0.0)
- [EntityFrameworkCore.Testing.NSubstitute - NuGet](https://www.nuget.org/packages/EntityFrameworkCore.Testing.NSubstitute/5.0.0)
### EntityFrameworkCore 6
- [Source](https://github.com/rgvlee/EntityFrameworkCore.Testing/tree/4.x)
- [EntityFrameworkCore.Testing.Moq - NuGet](https://www.nuget.org/packages/EntityFrameworkCore.Testing.Moq/4.0.2)
- [EntityFrameworkCore.Testing.NSubstitute - NuGet](https://www.nuget.org/packages/EntityFrameworkCore.Testing.NSubstitute/4.0.2)
### EntityFrameworkCore 5
- [Source](https://github.com/rgvlee/EntityFrameworkCore.Testing/tree/3.x)
- [EntityFrameworkCore.Testing.Moq - NuGet](https://www.nuget.org/packages/EntityFrameworkCore.Testing.Moq/3.0.5)
- [EntityFrameworkCore.Testing.NSubstitute - NuGet](https://www.nuget.org/packages/EntityFrameworkCore.Testing.NSubstitute/3.0.5)
### EntityFrameworkCore 3
- [Source](https://github.com/rgvlee/EntityFrameworkCore.Testing/tree/2.x)
- [EntityFrameworkCore.Testing.Moq - NuGet](https://www.nuget.org/packages/EntityFrameworkCore.Testing.Moq/2.4.5)
- [EntityFrameworkCore.Testing.NSubstitute - NuGet](https://www.nuget.org/packages/EntityFrameworkCore.Testing.NSubstitute/2.4.5)
### EntityFrameworkCore 2 (2.1.0+)
- [Source](https://github.com/rgvlee/EntityFrameworkCore.Testing/tree/1.x)
- [EntityFrameworkCore.Testing.Moq - NuGet](https://www.nuget.org/packages/EntityFrameworkCore.Testing.Moq/1.3.5)
- [EntityFrameworkCore.Testing.NSubstitute - NuGet](https://www.nuget.org/packages/EntityFrameworkCore.Testing.NSubstitute/1.3.5)
## Prerequisites
### An accessible constructor
Your db context must have an accessible constructor.
### Virtual sets/queries
Your db context set/query properties must be overridable:
```c#
public virtual DbSet TestEntities { get; set; }
```
## Creating a mocked DbContext
If your db context has an accessible constructor with a single `DbContextOptions` or `DbContextOptions` parameter, creating a mocked db context is as easy as:
```c#
var mockedDbContext = Create.MockedDbContextFor();
```
Any accessible constructor can be used provided it has a `DbContextOptions` or `DbContextOptions` parameter:
```c#
var mockedLogger = Mock.Of>();
var dbContextOptions = new DbContextOptionsBuilder().UseInMemoryDatabase(Guid.NewGuid().ToString()).Options;
var mockedDbContext = Create.MockedDbContextFor(mockedLogger, dbContextOptions);
```
Both of the above examples automatically create and use a Microsoft in-memory provider instance for the EntityFrameworkCore provider. If you want more control e.g., to specify the EntityFrameworkCore provider instance, use the builder:
```c#
var options = new DbContextOptionsBuilder().UseInMemoryDatabase(Guid.NewGuid().ToString()).Options;
var dbContextToMock = new TestDbContext(options);
var mockedDbContext = new MockedDbContextBuilder().UseDbContext(dbContextToMock).UseConstructorWithParameters(options).MockedDbContext;
```
There is no requirement to use the Microsoft in-memory provider. The following example uses the SQLite in-memory provider for a db context with a parameterless constructor:
```c#
using (var connection = new SqliteConnection("Filename=:memory:"))
{
connection.Open();
var testEntity = _fixture.Create();
var dbContextToMock = new TestDbContext(new DbContextOptionsBuilder().UseSqlite(connection).Options);
dbContextToMock.Database.EnsureCreated();
var mockedDbContext = new MockedDbContextBuilder().UseDbContext(dbContextToMock).MockedDbContext;
mockedDbContext.Set().Add(testEntity);
mockedDbContext.SaveChanges();
Assert.Multiple(() =>
{
Assert.AreNotEqual(default(Guid), testEntity.Id);
Assert.DoesNotThrow(() => mockedDbContext.Set().Single());
Assert.AreEqual(testEntity, mockedDbContext.Find(testEntity.Id));
});
}
```
## Usage
Start by creating a mocked db context and, if the SUT requires, populate it as if you were using the real thing:
```c#
var testEntity = _fixture.Create();
var mockedDbContext = Create.MockedDbContextFor();
mockedDbContext.Set().Add(testEntity);
mockedDbContext.SaveChanges();
Assert.Multiple(() =>
{
Assert.AreNotEqual(default(Guid), testEntity.Id);
Assert.DoesNotThrow(() => mockedDbContext.Set().Single());
Assert.AreEqual(testEntity, mockedDbContext.Find(testEntity.Id));
});
```
The Moq implementation of `Create.MockedDbContextFor()` returns the mocked db context. If you need the mock itself (e.g., to verify an invocation) use `Mock.Get(mockedDbSet)`:
```c#
var mockedDbContext = Create.MockedDbContextFor();
mockedDbContext.Set().AddRange(_fixture.CreateMany().ToList());
mockedDbContext.SaveChanges();
Assert.Multiple(() =>
{
var dbContextMock = Mock.Get(mockedDbContext);
dbContextMock.Verify(m => m.SaveChanges(), Times.Once);
});
```
### FromSql
Use `AddFromSqlResult` to add a from SQL result to the mock. The following will return `expectedResult` for any `FromSql` invocation:
```c#
var expectedResult = _fixture.CreateMany().ToList();
var mockedDbContext = Create.MockedDbContextFor();
mockedDbContext.Set().AddFromSqlRawResult(expectedResult);
var actualResult = mockedDbContext.Set().FromSqlRaw("[dbo].[USP_StoredProcedureWithNoParameters]").ToList();
Assert.Multiple(() =>
{
Assert.IsNotNull(actualResult);
Assert.IsTrue(actualResult.Any());
CollectionAssert.AreEquivalent(expectedResult, actualResult);
});
```
The following will return `expectedResult` if the `FromSql` SQL query text contains `usp_StoredProcedureWithParameters` and a `@Parameter2` SQL parameter with a value of `Value2` has been provided:
```c#
var expectedResult = _fixture.CreateMany().ToList();
var sqlParameters = new List { new SqlParameter("@Parameter2", "Value2") };
var mockedDbContext = Create.MockedDbContextFor();
mockedDbContext.Set().AddFromSqlRawResult("usp_StoredProcedureWithParameters", sqlParameters, expectedResult);
var actualResult = mockedDbContext.Set()
.FromSqlRaw("[dbo].[USP_StoredProcedureWithParameters] @Parameter1 @Parameter2",
new SqlParameter("@parameter1", "Value1"),
new SqlParameter("@parameter2", "value2"))
.ToList();
Assert.Multiple(() =>
{
Assert.IsNotNull(actualResult);
Assert.IsTrue(actualResult.Any());
CollectionAssert.AreEquivalent(expectedResult, actualResult);
});
```
SQL query text matching supports partial, case insensitive matches. Individual parameter name and value matching is also case insensitive. Case insensitive interpolated strings are also supported:
```c#
var expectedResult = _fixture.CreateMany().ToList();
var parameter1 = _fixture.Create();
var parameter2 = _fixture.Create();
var mockedDbContext = Create.MockedDbContextFor();
mockedDbContext.Set().AddFromSqlInterpolatedResult($"usp_StoredProcedureWithParameters {parameter1}, {parameter2.ToUpper()}", expectedResult);
var actualResult = mockedDbContext.Set().FromSqlInterpolated($"USP_StoredProcedureWithParameters {parameter1}, {parameter2.ToLower()}").ToList();
Assert.Multiple(() =>
{
Assert.IsNotNull(actualResult);
Assert.IsTrue(actualResult.Any());
CollectionAssert.AreEquivalent(expectedResult, actualResult);
});
```
### FromSqlRaw/FromSqlInterpolated (EntityFrameworkCore 3.\*)
Use `AddFromSqlRawResult` and `AddFromSqlInterpolatedResult` to add results for `FromSqlRaw` and `FromSqlInterpolated` invocations. Refer to the FromSql section above for usage.
### Queries
Use `AddToReadOnlySource`, `AddRangeToReadOnlySource` and `ClearReadOnlySource` to manage a query source.
```c#
var expectedResult = _fixture.CreateMany().ToList();
var mockedDbContext = Create.MockedDbContextFor();
mockedDbContext.Set().AddRangeToReadOnlySource(expectedResult);
Assert.Multiple(() =>
{
CollectionAssert.AreEquivalent(expectedResult, mockedDbContext.Set().ToList());
CollectionAssert.AreEquivalent(mockedDbContext.Set().ToList(), mockedDbContext.TestReadOnlyEntities.ToList());
});
```
Specifying a from SQL result for a query is exactly the same as for a set.
### Keyless Sets (EntityFrameworkCore 3.\*)
Refer to the Queries section above for usage.
### ExecuteSqlCommand
Adding an execute SQL command result is similar to adding a from SQL result with the main difference being the return type. `ExecuteSqlCommand` returns an `int` (the number of rows affected by executing the SQL command text).
```c#
var commandText = "usp_StoredProcedureWithNoParameters";
var expectedResult = 1;
var mockedDbContext = Create.MockedDbContextFor();
mockedDbContext.AddExecuteSqlRawResult(commandText, new List(), expectedResult);
var result = mockedDbContext.Database.ExecuteSqlRaw("USP_StoredProcedureWithNoParameters");
Assert.AreEqual(expectedResult, result);
```
All of the overloads have an optional `Action>` parameter which allows you to perform operations post invocation. The following provides a basic example where invoking `ExecuteSqlCommand` deletes a specified number of rows from a set:
```c#
//Arrange
var mockedDbContext = Create.MockedDbContextFor();
var itemsToCreate = 100;
mockedDbContext.Set().AddRange(_fixture.CreateMany(itemsToCreate).ToList());
mockedDbContext.SaveChanges();
var numberOfRowsToDelete = itemsToCreate / 2;
var rowsToDelete = mockedDbContext.Set().Take(numberOfRowsToDelete).ToList();
var remainingRows = mockedDbContext.Set().Skip(numberOfRowsToDelete).ToList();
mockedDbContext.AddExecuteSqlRawResult("usp_MyStoredProc",
numberOfRowsToDelete,
(providedSql, providedParameters) =>
{
mockedDbContext.Set().RemoveRange(rowsToDelete);
mockedDbContext.SaveChanges();
});
//Act
var actualResult = mockedDbContext.Database.ExecuteSqlRaw($"usp_MyStoredProc {numberOfRowsToDelete}");
//Assert
Assert.Multiple(() =>
{
Assert.That(actualResult, Is.EqualTo(numberOfRowsToDelete));
Assert.That(mockedDbContext.Set().Count(), Is.EqualTo(itemsToCreate - numberOfRowsToDelete));
Assert.That(mockedDbContext.Set().ToList(), Is.EquivalentTo(remainingRows));
});
```
### ExecuteSqlRaw/ExecuteSqlInterpolated (EntityFrameworkCore 3.\*)
Use `AddExecuteSqlRawResult` and `AddExecuteSqlInterpolatedResult` to add results for `ExecuteSqlRaw` and `ExecuteSqlInterpolated` invocations. Refer to the ExecuteSqlCommand section above for usage.
### Async and LINQ queryable operations
Whenever you add a from SQL or execute SQL command result, EntityFrameworkCore.Testing sets up both the sync and async methods. It also automatically provides support for all sync and async LINQ queryable operations that are not supported by the Microsoft in-memory provider.
### Asserting mock invocations
The db context and each set, query and their respective query providers are separate mocks. The following Moq example asserts that the `DbContext.SaveChanges` and `DbSet.AddRange` methods were both invoked once.
```c#
var mockedDbContext = Create.MockedDbContextFor();
mockedDbContext.Set().AddRange(_fixture.CreateMany().ToList());
mockedDbContext.SaveChanges();
var dbContextMock = Mock.Get(mockedDbContext);
dbContextMock.Verify(m => m.SaveChanges(), Times.Once);
var byTypeDbSetMock = Mock.Get(mockedDbContext.Set());
byTypeDbSetMock.Verify(m => m.AddRange(It.IsAny>()), Times.Once);
var byPropertyDbSetMock = Mock.Get(mockedDbContext.TestEntities);
byPropertyDbSetMock.Verify(m => m.AddRange(It.IsAny>()), Times.Once);
```
================================================
FILE: TODO.md
================================================
# TODO
- Add tests for untested functionality
- Remove repeated set up code
- Unify test structures to assist with cross project comparisons
- Add default behaviour tests for SQL Server provider
================================================
FILE: googlea6bd68d4a55b1e59.html
================================================
google-site-verification: googlea6bd68d4a55b1e59.html
================================================
FILE: src/EntityFrameworkCore.DefaultBehaviour.Tests/ByTypeDbSetTests.cs
================================================
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using AutoFixture;
using EntityFrameworkCore.Testing.Common.Tests;
using FluentAssertions;
using Microsoft.EntityFrameworkCore;
using NUnit.Framework;
using static FluentAssertions.FluentActions;
namespace EntityFrameworkCore.DefaultBehaviour.Tests;
public class ByTypeDbSetTests : BaseForQueryableTests
{
protected TestDbContext DbContext;
protected DbSet DbSet => DbContext.Set();
protected override IQueryable Queryable => DbSet;
[SetUp]
public override void SetUp()
{
base.SetUp();
DbContext = new TestDbContext(new DbContextOptionsBuilder().UseInMemoryDatabase(Guid.NewGuid().ToString()).Options);
}
protected override void SeedQueryableSource()
{
var itemsToAdd = Fixture.Build().With(p => p.CreatedAt, DateTime.Today).With(p => p.LastModifiedAt, DateTime.Today).CreateMany().ToList();
DbContext.Set().AddRange(itemsToAdd);
DbContext.SaveChanges();
ItemsAddedToQueryableSource = itemsToAdd;
}
[Test]
public virtual async Task AsAsyncEnumerable_ReturnsAsyncEnumerable()
{
var expectedResult = Fixture.Create();
DbSet.Add(expectedResult);
DbContext.SaveChanges();
var asyncEnumerable = DbSet.AsAsyncEnumerable();
var actualResults = new List();
await foreach (var item in asyncEnumerable) actualResults.Add(item);
Assert.Multiple(() =>
{
Assert.That(actualResults.Single(), Is.EqualTo(expectedResult));
Assert.That(actualResults.Single(), Is.EqualTo(expectedResult));
});
}
[Test]
public virtual void AsQueryable_ReturnsQueryable()
{
var expectedResult = Fixture.Create();
DbSet.Add(expectedResult);
DbContext.SaveChanges();
var queryable = DbSet.AsQueryable();
Assert.Multiple(() =>
{
Assert.That(queryable.Single(), Is.EqualTo(expectedResult));
Assert.That(queryable.Single(), Is.EqualTo(expectedResult));
});
}
[Test]
public virtual void FromSqlInterpolated_ThrowsException()
{
Invoking(() => DbSet.FromSqlInterpolated($"sp_NoParams").ToList()).Should().ThrowExactly();
}
[Test]
public virtual void FromSqlRaw_ThrowsException()
{
Invoking(() => DbSet.FromSqlRaw("sp_NoParams").ToList()).Should().ThrowExactly();
}
}
================================================
FILE: src/EntityFrameworkCore.DefaultBehaviour.Tests/ByTypeReadOnlyDbSetExceptionTests.cs
================================================
using System;
using EntityFrameworkCore.Testing.Common.Tests;
using Microsoft.EntityFrameworkCore;
using NUnit.Framework;
namespace EntityFrameworkCore.DefaultBehaviour.Tests
{
public class ReadOnlyDbSetExceptionTests : ReadOnlyDbSetExceptionTests
{
protected TestDbContext DbContext;
protected override DbSet DbSet => DbContext.Set();
[SetUp]
public override void SetUp()
{
base.SetUp();
DbContext = new TestDbContext(new DbContextOptionsBuilder().UseInMemoryDatabase(Guid.NewGuid().ToString()).Options);
}
}
}
================================================
FILE: src/EntityFrameworkCore.DefaultBehaviour.Tests/ByTypeReadOnlyDbSetTests.cs
================================================
using System;
using System.ComponentModel;
using EntityFrameworkCore.Testing.Common.Tests;
using Microsoft.EntityFrameworkCore;
using NUnit.Framework;
namespace EntityFrameworkCore.DefaultBehaviour.Tests
{
public class ByTypeReadOnlyDbSetTests : BaseForTests
{
protected TestDbContext DbContext;
protected DbSet DbSet => DbContext.Set();
[SetUp]
public override void SetUp()
{
base.SetUp();
DbContext = new TestDbContext(new DbContextOptionsBuilder().UseInMemoryDatabase(Guid.NewGuid().ToString()).Options);
}
[Test]
public virtual void AsAsyncEnumerable_ReturnsAsyncEnumerable()
{
var asyncEnumerable = DbSet.AsAsyncEnumerable();
Assert.That(asyncEnumerable, Is.Not.Null);
}
[Test]
public virtual void AsQueryable_ReturnsQueryable()
{
var queryable = DbSet.AsQueryable();
Assert.That(queryable, Is.Not.Null);
}
[Test]
public void ContainsListCollection_ReturnsFalse()
{
var containsListCollection = ((IListSource) DbSet).ContainsListCollection;
Assert.That(containsListCollection, Is.False);
}
}
}
================================================
FILE: src/EntityFrameworkCore.DefaultBehaviour.Tests/DbContextTests.cs
================================================
using System;
using System.Linq;
using EntityFrameworkCore.Testing.Common;
using EntityFrameworkCore.Testing.Common.Tests;
using Microsoft.EntityFrameworkCore;
using NUnit.Framework;
namespace EntityFrameworkCore.DefaultBehaviour.Tests
{
public class DbContextTests : BaseForTests
{
protected TestDbContext DbContext;
[SetUp]
public override void SetUp()
{
base.SetUp();
DbContext = new TestDbContext(new DbContextOptionsBuilder().UseInMemoryDatabase(Guid.NewGuid().ToString()).Options);
}
[Test]
public virtual void ExecuteSqlInterpolated_ThrowsException()
{
Assert.Throws(() =>
{
var actualResult = DbContext.Database.ExecuteSqlInterpolated($"sp_NoParams");
});
}
[Test]
public virtual void ExecuteSqlRaw_ThrowsException()
{
Assert.Throws(() =>
{
var actualResult = DbContext.Database.ExecuteSqlRaw("sp_NoParams");
});
}
[Test]
public virtual void Set_TypeNotIncludedInModel_ThrowsException()
{
Assert.Multiple(() =>
{
var ex = Assert.Throws(() => DbContext.Set().ToList());
Assert.That(ex.Message, Is.EqualTo(string.Format(ExceptionMessages.CannotCreateDbSetTypeNotIncludedInModel, nameof(NotRegisteredEntity))));
});
}
[Test]
public virtual void SetCommandTimeout_ValidTimeout_ThrowsException()
{
Assert.Throws(() =>
{
DbContext.Database.SetCommandTimeout(60);
});
}
[Test]
public virtual void GetCommandTimeout_ThrowsException()
{
Assert.Throws(() =>
{
DbContext.Database.GetCommandTimeout();
});
}
}
}
================================================
FILE: src/EntityFrameworkCore.DefaultBehaviour.Tests/EntityFrameworkCore.DefaultBehaviour.Tests.csproj
================================================
net10.0falseNU1605trueNU1605allruntime; build; native; contentfiles; analyzers; buildtransitive
================================================
FILE: src/EntityFrameworkCore.DefaultBehaviour.Tests/Issue114Tests.cs
================================================
using System;
using Microsoft.EntityFrameworkCore;
namespace EntityFrameworkCore.DefaultBehaviour.Tests
{
public class Issue114Tests : Testing.Common.Tests.Issue114Tests
{
protected override TestDbContext MockedDbContextFactory()
{
return new TestDbContext(new DbContextOptionsBuilder().UseInMemoryDatabase(Guid.NewGuid().ToString()).Options);
}
}
}
================================================
FILE: src/EntityFrameworkCore.DefaultBehaviour.Tests/Issue117Tests.cs
================================================
using System;
using Microsoft.EntityFrameworkCore;
namespace EntityFrameworkCore.DefaultBehaviour.Tests
{
public class Issue117Tests : Testing.Common.Tests.Issue117Tests
{
protected override TestDbContext MockedDbContextFactory()
{
return new TestDbContext(new DbContextOptionsBuilder().UseInMemoryDatabase(Guid.NewGuid().ToString()).Options);
}
}
}
================================================
FILE: src/EntityFrameworkCore.DefaultBehaviour.Tests/Issue49Tests.cs
================================================
using System;
using EntityFrameworkCore.Testing.Common.Tests;
using Microsoft.EntityFrameworkCore;
using NUnit.Framework;
namespace EntityFrameworkCore.DefaultBehaviour.Tests
{
public class Issue49Tests : Issue49Tests
{
[SetUp]
public override void SetUp()
{
base.SetUp();
DbContext = new TestDbContext(new DbContextOptionsBuilder().UseInMemoryDatabase(Guid.NewGuid().ToString()).Options);
}
}
}
================================================
FILE: src/EntityFrameworkCore.DefaultBehaviour.Tests/Issue88Tests.cs
================================================
using System;
using EntityFrameworkCore.Testing.Common.Tests;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Diagnostics;
using NUnit.Framework;
namespace EntityFrameworkCore.DefaultBehaviour.Tests
{
public class Issue88Tests : Issue88Tests
{
[SetUp]
public override void SetUp()
{
base.SetUp();
var options = new DbContextOptionsBuilder()
.UseInMemoryDatabase(Guid.NewGuid().ToString())
.ConfigureWarnings(x => x.Ignore(InMemoryEventId.TransactionIgnoredWarning))
.Options;
DbContextFactory = () => new TestDbContext(options);
}
}
}
================================================
FILE: src/EntityFrameworkCore.Testing.Common/AsyncEnumerable.cs
================================================
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Threading;
using Microsoft.EntityFrameworkCore.Query;
namespace EntityFrameworkCore.Testing.Common
{
public class AsyncEnumerable : IAsyncEnumerable, IOrderedQueryable
{
private readonly IQueryable _source;
public AsyncEnumerable(IEnumerable enumerable)
{
_source = enumerable.AsQueryable();
Provider = new AsyncQueryProvider(_source);
Expression = _source.Expression;
}
public AsyncEnumerable(IEnumerable enumerable, QueryRootExpression expression) : this(enumerable)
{
Expression = expression;
}
public IAsyncEnumerator GetAsyncEnumerator(CancellationToken cancellationToken = new())
{
return new AsyncEnumerator(_source);
}
IEnumerator IEnumerable.GetEnumerator()
{
return _source.GetEnumerator();
}
IEnumerator IEnumerable.GetEnumerator()
{
return _source.GetEnumerator();
}
public Type ElementType => typeof(T);
public Expression Expression { get; }
public IQueryProvider Provider { get; }
}
}
================================================
FILE: src/EntityFrameworkCore.Testing.Common/AsyncEnumerator.cs
================================================
using System.Collections.Generic;
using System.Threading.Tasks;
namespace EntityFrameworkCore.Testing.Common
{
public class AsyncEnumerator : IAsyncEnumerator
{
private readonly IEnumerator _enumerator;
public AsyncEnumerator(IEnumerable enumerable)
{
_enumerator = enumerable.GetEnumerator();
}
public ValueTask DisposeAsync()
{
return new();
}
public ValueTask MoveNextAsync()
{
return new(_enumerator.MoveNext());
}
public T Current => _enumerator.Current;
}
}
================================================
FILE: src/EntityFrameworkCore.Testing.Common/AsyncQueryProvider.cs
================================================
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.EntityFrameworkCore.Query;
using Microsoft.EntityFrameworkCore.Query.Internal;
using Microsoft.Extensions.Logging;
using rgvlee.Core.Common.Helpers;
using ProjectExpressionHelper = EntityFrameworkCore.Testing.Common.Helpers.ExpressionHelper;
namespace EntityFrameworkCore.Testing.Common
{
///
public class AsyncQueryProvider : IAsyncQueryProvider
{
private static readonly ILogger Logger = LoggingHelper.CreateLogger>();
public AsyncQueryProvider(IEnumerable enumerable)
{
Source = enumerable.AsQueryable();
}
///
/// The query provider source.
///
public IQueryable Source { get; set; }
///
/// In this implementation it is just a wrapper for
public virtual IQueryable CreateQuery(Expression expression)
{
Logger.LogDebug("CreateQuery: invoked");
//Handles cases where we are projecting to another type
if (expression is MethodCallExpression mce)
{
var returnType = mce.Method.ReturnType;
if (returnType.GetGenericTypeDefinition() != typeof(IQueryable<>))
{
throw new InvalidOperationException($"Expected IQueryable<>; actual {returnType.FullName}");
}
var createQueryMethod = typeof(IQueryProvider).GetMethods().Single(x => x.Name.Equals(nameof(IQueryProvider.CreateQuery)) && x.IsGenericMethod);
var createQueryResult = createQueryMethod.MakeGenericMethod(returnType.GetGenericArguments().Single()).Invoke(this, new[] { expression });
return (IQueryable) Activator.CreateInstance(typeof(AsyncEnumerable<>).GetGenericTypeDefinition().MakeGenericType(returnType.GetGenericArguments().Single()),
createQueryResult);
}
return CreateQuery(expression);
}
///
public virtual IQueryable CreateQuery(Expression expression)
{
Logger.LogDebug("CreateQuery: invoked");
if (expression is FromSqlQueryRootExpression)
{
Logger.LogDebug("CreateQuery: catch all exception invoked");
throw new NotSupportedException();
}
ProjectExpressionHelper.ThrowIfExpressionIsNotSupported(expression);
return new AsyncEnumerable(Source.Provider.CreateQuery(EnsureExpressionCanBeResolvedBySourceProvider(expression)));
}
///
public virtual object Execute(Expression expression)
{
Logger.LogDebug("Execute: invoked");
ProjectExpressionHelper.ThrowIfExpressionIsNotSupported(expression);
return Source.Provider.Execute(EnsureExpressionCanBeResolvedBySourceProvider(expression));
}
///
public virtual TResult Execute(Expression expression)
{
Logger.LogDebug("Execute: invoked");
ProjectExpressionHelper.ThrowIfExpressionIsNotSupported(expression);
return Source.Provider.Execute(EnsureExpressionCanBeResolvedBySourceProvider(expression));
}
///
public virtual TResult ExecuteAsync(Expression expression, CancellationToken cancellationToken)
{
//TResult is a Task. The provider requires T.
return (TResult) typeof(AsyncQueryProvider).GetMethod(nameof(WrapExecuteAsync), BindingFlags.Instance | BindingFlags.NonPublic)
.MakeGenericMethod(typeof(TResult).GetGenericArguments())
.Invoke(this, new object[] { expression, cancellationToken });
}
private Task WrapExecuteAsync(Expression expression, CancellationToken cancellationToken)
{
return Task.FromResult(Execute(expression));
}
private Expression EnsureExpressionCanBeResolvedBySourceProvider(Expression expression)
{
Logger.LogDebug("EnsureExpressionCanBeResolvedBySourceProvider: invoked");
if (expression is MethodCallExpression mce && mce.Arguments[0] is Microsoft.EntityFrameworkCore.Query.QueryRootExpression)
{
for (var i = 0; i < mce.Arguments.Count; i++)
{
Logger.LogDebug("argument[{i}]: {argument}", i, mce.Arguments[i].ToString());
}
//This ensures that Source provider will always be able to resolve the expression
var arguments = new List();
arguments.Add(Source.Expression);
arguments.AddRange(mce.Arguments.Skip(1));
Logger.LogDebug("sourceExpression: {sourceExpression}", Source.Expression.ToString());
for (var i = 0; i < mce.Arguments.Count; i++)
{
Logger.LogDebug("argument[{i}]: {argument}", i, mce.Arguments[i].ToString());
}
return Expression.Call(mce.Method, arguments);
}
return expression;
}
}
}
================================================
FILE: src/EntityFrameworkCore.Testing.Common/EntityFrameworkCore.Testing.Common.csproj
================================================
net10.0rgvleeEntityFrameworkCore.Testing.Common.xmlNU1605EntityFrameworkCore.Testing.Common.xmltrueNU1605TrueTrueExceptionMessages.resxPublicResXFileCodeGeneratorExceptionMessages.Designer.cs
================================================
FILE: src/EntityFrameworkCore.Testing.Common/EntityFrameworkCore.Testing.Common.xml
================================================
EntityFrameworkCore.Testing.Common
The query provider source.
In this implementation it is just a wrapper for
A strongly-typed resource class, for looking up localized strings, etc.
Returns the cached ResourceManager instance used by this class.
Overrides the current thread's CurrentUICulture property for all
resource lookups using this strongly typed resource class.
Looks up a localized string similar to Cannot create a DbSet for '{0}' because this type is not included in the model for the context..
Looks up a localized string similar to Unable to find a suitable constructor. TDbContext must have a parameterless or DbContextOptions/DbContextOptions<TDbContext> constructor..
The mocked db context builder.
The db context type.
The create factory options.
The mocked db context.
The parameters that will be used to create the mocked db context and, if one is not provided,
the in-memory context that the mocked db context will use for in-memory provider supported operations.
The constructor parameters.
The mocked db context builder.
The db context instance that the mocked db context will use for in-memory provider supported operations.
The base mocked db context factory.
The db context type.
The logger instance.
The parameters that will be used to create the mocked db context and, if one is not provided,
the in-memory context that the mocked db context will use for in-memory provider supported operations.
The db context instance that the mocked db context will use for in-memory provider supported operations.
Constructor.
The mocked db context factory options.
Creates and sets up a mocked db context.
A mocked db context.
A helper for expressions.
Creates a property expression for the specified property.
The expression parameter.The expression property.
The property info of the property to create the expression for.
A property expression for the specified property.
The mocked db context builder.
The db context type.
The mocked db context.
The parameters that will be used to create the mocked db context and, if one is not provided,
the in-memory context that the mocked db context will use for in-memory provider supported operations.
The constructor parameters.
The mocked db context builder.
The db context instance that the mocked db context will use for in-memory provider supported operations.
The mocked db context factory options.
The db context type.
The db context instance that the mocked db context will use for in-memory provider supported operations.
The parameters that will be used to create the mocked db context and, if one is not provided,
the in-memory context that the mocked db context will use for in-memory provider supported operations.
A helper for parameter matching.
Determines whether the invocation parameters match the set up parameters.
The set up parameters.
The invocation parameters.
true the invocation parameters are a partial or full match of the set up parameters.
If the parameters are DbParameters, parameter name and value are compared.
Parameter name matching is case insensitive.
If the value is a string, the matching is case insensitive.
For everything else an exact match is required.
Converts a sequence of invocation parameters to a string of parameter names and values.
The invocation parameters.
A string of parameter names and values.
================================================
FILE: src/EntityFrameworkCore.Testing.Common/ExceptionMessages.Designer.cs
================================================
//------------------------------------------------------------------------------
//
// This code was generated by a tool.
// Runtime Version:4.0.30319.42000
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
//
//------------------------------------------------------------------------------
namespace EntityFrameworkCore.Testing.Common {
using System;
///
/// A strongly-typed resource class, for looking up localized strings, etc.
///
// This class was auto-generated by the StronglyTypedResourceBuilder
// class via a tool like ResGen or Visual Studio.
// To add or remove a member, edit your .ResX file then rerun ResGen
// with the /str option, or rebuild your VS project.
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "4.0.0.0")]
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
public class ExceptionMessages {
private static global::System.Resources.ResourceManager resourceMan;
private static global::System.Globalization.CultureInfo resourceCulture;
[global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
internal ExceptionMessages() {
}
///
/// Returns the cached ResourceManager instance used by this class.
///
[global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
public static global::System.Resources.ResourceManager ResourceManager {
get {
if (object.ReferenceEquals(resourceMan, null)) {
global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("EntityFrameworkCore.Testing.Common.ExceptionMessages", typeof(ExceptionMessages).Assembly);
resourceMan = temp;
}
return resourceMan;
}
}
///
/// Overrides the current thread's CurrentUICulture property for all
/// resource lookups using this strongly typed resource class.
///
[global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
public static global::System.Globalization.CultureInfo Culture {
get {
return resourceCulture;
}
set {
resourceCulture = value;
}
}
///
/// Looks up a localized string similar to Cannot create a DbSet for '{0}' because this type is not included in the model for the context..
///
public static string CannotCreateDbSetTypeNotIncludedInModel {
get {
return ResourceManager.GetString("CannotCreateDbSetTypeNotIncludedInModel", resourceCulture);
}
}
///
/// Looks up a localized string similar to Unable to find a suitable constructor. TDbContext must have a parameterless or DbContextOptions/DbContextOptions<TDbContext> constructor..
///
public static string UnableToFindSuitableDbContextConstructor {
get {
return ResourceManager.GetString("UnableToFindSuitableDbContextConstructor", resourceCulture);
}
}
}
}
================================================
FILE: src/EntityFrameworkCore.Testing.Common/ExceptionMessages.resx
================================================
text/microsoft-resx2.0System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089Cannot create a DbSet for '{0}' because this type is not included in the model for the context.Unable to find a suitable constructor. TDbContext must have a parameterless or DbContextOptions/DbContextOptions<TDbContext> constructor.
================================================
FILE: src/EntityFrameworkCore.Testing.Common/Helpers/BaseMockedDbContextBuilder.cs
================================================
using Microsoft.EntityFrameworkCore;
using rgvlee.Core.Common.Helpers;
namespace EntityFrameworkCore.Testing.Common.Helpers
{
///
/// The mocked db context builder.
///
/// The db context type.
public abstract class BaseMockedDbContextBuilder : IMockedDbContextBuilder where TDbContext : DbContext
{
///
/// The create factory options.
///
protected readonly MockedDbContextFactoryOptions Options = new();
///
/// The mocked db context.
///
public abstract TDbContext MockedDbContext { get; }
///
/// The parameters that will be used to create the mocked db context and, if one is not provided,
/// the in-memory context that the mocked db context will use for in-memory provider supported operations.
///
///
/// The constructor parameters.
///
/// The mocked db context builder.
public IMockedDbContextBuilder UseConstructorWithParameters(params object[] constructorParameters)
{
EnsureArgument.IsNotEmpty(constructorParameters, nameof(constructorParameters));
Options.ConstructorParameters = constructorParameters;
return this;
}
///
/// The db context instance that the mocked db context will use for in-memory provider supported operations.
///
public IMockedDbContextBuilder UseDbContext(TDbContext dbContext)
{
EnsureArgument.IsNotNull(dbContext, nameof(dbContext));
Options.DbContext = dbContext;
return this;
}
}
}
================================================
FILE: src/EntityFrameworkCore.Testing.Common/Helpers/BaseMockedDbContextFactory.cs
================================================
using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Logging;
using rgvlee.Core.Common.Extensions;
using rgvlee.Core.Common.Helpers;
namespace EntityFrameworkCore.Testing.Common.Helpers
{
///
/// The base mocked db context factory.
///
/// The db context type.
public abstract class BaseMockedDbContextFactory where TDbContext : DbContext
{
///
/// The logger instance.
///
protected static readonly ILogger Logger = LoggingHelper.CreateLogger>();
///
/// The parameters that will be used to create the mocked db context and, if one is not provided,
/// the in-memory context that the mocked db context will use for in-memory provider supported operations.
///
protected readonly List