├── .editorconfig ├── .gitignore ├── .vscode └── tasks.json ├── DbMocker.Tests ├── DatabaseCommandTests.cs ├── DbMockCallbackTests.cs ├── DbMockDatasetTests.cs ├── DbMockResourceTests.cs ├── DbMockSqlParserTests.cs ├── DbMockTableFromTypeTests.cs ├── DbMockTableTests.cs ├── DbMockTagsTests.cs ├── DbMockTests.cs ├── DbMocker.Tests.csproj ├── SampleTypes │ ├── NavgiationModel.cs │ ├── RelatedModel.cs │ └── SimpleModel.cs ├── Samples.cs ├── Samples │ ├── 123-EMPLOYEES.txt │ ├── SampleTable1.txt │ ├── SampleTable2.txt │ └── XX-SampleTable1.txt └── Samples_EFTests.cs ├── DbMocker.sln ├── DbMocker ├── Data │ ├── MockDbCommand.cs │ ├── MockDbDataReader.cs │ ├── MockDbParameter.cs │ ├── MockDbParameterCollection.cs │ └── MockDbTransaction.cs ├── DbMocker.csproj ├── Helpers │ ├── ArrayExtensions.cs │ ├── DbTypeMap.cs │ ├── DbTypeSchemaDescriptor.cs │ ├── MockDataReaderSchemaTableBuilder.cs │ └── TypeExtension.cs ├── MockColumn.cs ├── MockCommand.cs ├── MockConditions.cs ├── MockDbConnection.cs ├── MockException.cs ├── MockResourceOptions.cs ├── MockReturns.cs ├── MockTable.cs ├── MockTableFromType.cs ├── MockTableImport.cs ├── MockTableImportFixed.cs └── MockTableStatic.cs ├── LICENSE ├── ReadMe.md └── spelling.dic /.editorconfig: -------------------------------------------------------------------------------- 1 | # EditorConfig is awesome: https://EditorConfig.org 2 | 3 | # This is the default for the codeline. 4 | root = true 5 | 6 | [*] 7 | indent_style = space 8 | charset = utf-8 9 | trim_trailing_whitespace = true 10 | insert_final_newline = true 11 | spelling_exclusion_path = ./spelling.dic 12 | 13 | [*.cs] 14 | indent_size = 4 15 | 16 | [*.json] 17 | indent_size = 2 -------------------------------------------------------------------------------- /.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/2017 cache/options directory 28 | .vs/ 29 | # Uncomment if you have tasks that create the project's static files in wwwroot 30 | #wwwroot/ 31 | 32 | # Visual Studio 2017 auto generated files 33 | Generated\ Files/ 34 | 35 | # MSTest test Results 36 | [Tt]est[Rr]esult*/ 37 | [Bb]uild[Ll]og.* 38 | 39 | # NUNIT 40 | *.VisualState.xml 41 | TestResult.xml 42 | 43 | # Build Results of an ATL Project 44 | [Dd]ebugPS/ 45 | [Rr]eleasePS/ 46 | dlldata.c 47 | 48 | # Benchmark Results 49 | BenchmarkDotNet.Artifacts/ 50 | 51 | # .NET Core 52 | project.lock.json 53 | project.fragment.lock.json 54 | artifacts/ 55 | **/Properties/launchSettings.json 56 | 57 | # StyleCop 58 | StyleCopReport.xml 59 | 60 | # Files built by Visual Studio 61 | *_i.c 62 | *_p.c 63 | *_i.h 64 | *.ilk 65 | *.meta 66 | *.obj 67 | *.iobj 68 | *.pch 69 | *.pdb 70 | *.ipdb 71 | *.pgc 72 | *.pgd 73 | *.rsp 74 | *.sbr 75 | *.tlb 76 | *.tli 77 | *.tlh 78 | *.tmp 79 | *.tmp_proj 80 | *.log 81 | *.vspscc 82 | *.vssscc 83 | .builds 84 | *.pidb 85 | *.svclog 86 | *.scc 87 | 88 | # Chutzpah Test files 89 | _Chutzpah* 90 | 91 | # Visual C++ cache files 92 | ipch/ 93 | *.aps 94 | *.ncb 95 | *.opendb 96 | *.opensdf 97 | *.sdf 98 | *.cachefile 99 | *.VC.db 100 | *.VC.VC.opendb 101 | 102 | # Visual Studio profiler 103 | *.psess 104 | *.vsp 105 | *.vspx 106 | *.sap 107 | 108 | # Visual Studio Trace Files 109 | *.e2e 110 | 111 | # TFS 2012 Local Workspace 112 | $tf/ 113 | 114 | # Guidance Automation Toolkit 115 | *.gpState 116 | 117 | # ReSharper is a .NET coding add-in 118 | _ReSharper*/ 119 | *.[Rr]e[Ss]harper 120 | *.DotSettings.user 121 | 122 | # JustCode is a .NET coding add-in 123 | .JustCode 124 | 125 | # TeamCity is a build add-in 126 | _TeamCity* 127 | 128 | # DotCover is a Code Coverage Tool 129 | *.dotCover 130 | 131 | # AxoCover is a Code Coverage Tool 132 | .axoCover/* 133 | !.axoCover/settings.json 134 | 135 | # Visual Studio code coverage results 136 | *.coverage 137 | *.coveragexml 138 | 139 | # NCrunch 140 | _NCrunch_* 141 | .*crunch*.local.xml 142 | nCrunchTemp_* 143 | 144 | # MightyMoose 145 | *.mm.* 146 | AutoTest.Net/ 147 | 148 | # Web workbench (sass) 149 | .sass-cache/ 150 | 151 | # Installshield output folder 152 | [Ee]xpress/ 153 | 154 | # DocProject is a documentation generator add-in 155 | DocProject/buildhelp/ 156 | DocProject/Help/*.HxT 157 | DocProject/Help/*.HxC 158 | DocProject/Help/*.hhc 159 | DocProject/Help/*.hhk 160 | DocProject/Help/*.hhp 161 | DocProject/Help/Html2 162 | DocProject/Help/html 163 | 164 | # Click-Once directory 165 | publish/ 166 | 167 | # Publish Web Output 168 | *.[Pp]ublish.xml 169 | *.azurePubxml 170 | # Note: Comment the next line if you want to checkin your web deploy settings, 171 | # but database connection strings (with potential passwords) will be unencrypted 172 | *.pubxml 173 | *.publishproj 174 | 175 | # Microsoft Azure Web App publish settings. Comment the next line if you want to 176 | # checkin your Azure Web App publish settings, but sensitive information contained 177 | # in these scripts will be unencrypted 178 | PublishScripts/ 179 | 180 | # NuGet Packages 181 | *.nupkg 182 | # The packages folder can be ignored because of Package Restore 183 | **/[Pp]ackages/* 184 | # except build/, which is used as an MSBuild target. 185 | !**/[Pp]ackages/build/ 186 | # Uncomment if necessary however generally it will be regenerated when needed 187 | #!**/[Pp]ackages/repositories.config 188 | # NuGet v3's project.json files produces more ignorable files 189 | *.nuget.props 190 | *.nuget.targets 191 | 192 | # Microsoft Azure Build Output 193 | csx/ 194 | *.build.csdef 195 | 196 | # Microsoft Azure Emulator 197 | ecf/ 198 | rcf/ 199 | 200 | # Windows Store app package directories and files 201 | AppPackages/ 202 | BundleArtifacts/ 203 | Package.StoreAssociation.xml 204 | _pkginfo.txt 205 | *.appx 206 | 207 | # Visual Studio cache files 208 | # files ending in .cache can be ignored 209 | *.[Cc]ache 210 | # but keep track of directories ending in .cache 211 | !*.[Cc]ache/ 212 | 213 | # Others 214 | ClientBin/ 215 | ~$* 216 | *~ 217 | *.dbmdl 218 | *.dbproj.schemaview 219 | *.jfm 220 | *.pfx 221 | *.publishsettings 222 | orleans.codegen.cs 223 | 224 | # Including strong name files can present a security risk 225 | # (https://github.com/github/gitignore/pull/2483#issue-259490424) 226 | #*.snk 227 | 228 | # Since there are multiple workflows, uncomment next line to ignore bower_components 229 | # (https://github.com/github/gitignore/pull/1529#issuecomment-104372622) 230 | #bower_components/ 231 | 232 | # RIA/Silverlight projects 233 | Generated_Code/ 234 | 235 | # Backup & report files from converting an old project file 236 | # to a newer Visual Studio version. Backup files are not needed, 237 | # because we have git ;-) 238 | _UpgradeReport_Files/ 239 | Backup*/ 240 | UpgradeLog*.XML 241 | UpgradeLog*.htm 242 | ServiceFabricBackup/ 243 | *.rptproj.bak 244 | 245 | # SQL Server files 246 | *.mdf 247 | *.ldf 248 | *.ndf 249 | 250 | # Business Intelligence projects 251 | *.rdl.data 252 | *.bim.layout 253 | *.bim_*.settings 254 | *.rptproj.rsuser 255 | 256 | # Microsoft Fakes 257 | FakesAssemblies/ 258 | 259 | # GhostDoc plugin setting file 260 | *.GhostDoc.xml 261 | 262 | # Node.js Tools for Visual Studio 263 | .ntvs_analysis.dat 264 | node_modules/ 265 | 266 | # Visual Studio 6 build log 267 | *.plg 268 | 269 | # Visual Studio 6 workspace options file 270 | *.opt 271 | 272 | # Visual Studio 6 auto-generated workspace file (contains which files were open etc.) 273 | *.vbw 274 | 275 | # Visual Studio LightSwitch build output 276 | **/*.HTMLClient/GeneratedArtifacts 277 | **/*.DesktopClient/GeneratedArtifacts 278 | **/*.DesktopClient/ModelManifest.xml 279 | **/*.Server/GeneratedArtifacts 280 | **/*.Server/ModelManifest.xml 281 | _Pvt_Extensions 282 | 283 | # Paket dependency manager 284 | .paket/paket.exe 285 | paket-files/ 286 | 287 | # FAKE - F# Make 288 | .fake/ 289 | 290 | # JetBrains Rider 291 | .idea/ 292 | *.sln.iml 293 | 294 | # CodeRush 295 | .cr/ 296 | 297 | # Python Tools for Visual Studio (PTVS) 298 | __pycache__/ 299 | *.pyc 300 | 301 | # Cake - Uncomment if you are using it 302 | # tools/** 303 | # !tools/packages.config 304 | 305 | # Tabs Studio 306 | *.tss 307 | 308 | # Telerik's JustMock configuration file 309 | *.jmconfig 310 | 311 | # BizTalk build output 312 | *.btp.cs 313 | *.btm.cs 314 | *.odx.cs 315 | *.xsd.cs 316 | 317 | # OpenCover UI analysis results 318 | OpenCover/ 319 | 320 | # Azure Stream Analytics local run output 321 | ASALocalRun/ 322 | 323 | # MSBuild Binary and Structured Log 324 | *.binlog 325 | 326 | # NVidia Nsight GPU debugger configuration file 327 | *.nvuser 328 | 329 | # MFractors (Xamarin productivity tool) working folder 330 | .mfractor/ 331 | -------------------------------------------------------------------------------- /.vscode/tasks.json: -------------------------------------------------------------------------------- 1 | { 2 | // See https://go.microsoft.com/fwlink/?LinkId=733558 3 | // for the documentation about the tasks.json format 4 | "version": "2.0.0", 5 | "tasks": [ 6 | { 7 | "label": "build", 8 | "command": "dotnet", 9 | "type": "shell", 10 | "args": [ 11 | "build", 12 | // Ask dotnet build to generate full paths for file names. 13 | "/property:GenerateFullPaths=true", 14 | // Do not generate summary otherwise it leads to duplicate errors in Problems panel 15 | "/consoleloggerparameters:NoSummary" 16 | ], 17 | "group": "build", 18 | "presentation": { 19 | "reveal": "silent" 20 | }, 21 | "problemMatcher": "$msCompile" 22 | } 23 | ] 24 | } -------------------------------------------------------------------------------- /DbMocker.Tests/DatabaseCommandTests.cs: -------------------------------------------------------------------------------- 1 | using Apps72.Dev.Data; 2 | using Apps72.Dev.Data.DbMocker; 3 | using Microsoft.VisualStudio.TestTools.UnitTesting; 4 | using System; 5 | using System.Data.Common; 6 | using System.Data; 7 | using System.Data.SqlClient; 8 | using System.Linq; 9 | using System.Threading.Tasks; 10 | using System.Collections.Generic; 11 | 12 | namespace DbMocker.Tests 13 | { 14 | [TestClass] 15 | public class DatabaseCommandTests 16 | { 17 | [TestMethod] 18 | public void Mock_ContainsSql_IntegerScalar_Test() 19 | { 20 | var conn = new MockDbConnection(); 21 | 22 | conn.Mocks 23 | .When(c => c.CommandText.Contains("SELECT")) 24 | .ReturnsScalar(14); 25 | 26 | using (var cmd = new DatabaseCommand(conn)) 27 | { 28 | cmd.CommandText.AppendLine("SELECT * FROM EMP WHERE ID = @ID"); 29 | cmd.AddParameter("@ID", 1); 30 | var result = cmd.ExecuteScalar(); 31 | 32 | Assert.AreEqual(14, result); 33 | } 34 | } 35 | 36 | [TestMethod] 37 | public void Mock_ContainsSql_IntegerScalar_Null_Test() 38 | { 39 | var conn = new MockDbConnection(); 40 | 41 | conn.Mocks 42 | .When(c => c.CommandText.Contains("SELECT")) 43 | .ReturnsScalar((int?)null); 44 | 45 | using (var cmd = new DatabaseCommand(conn)) 46 | { 47 | cmd.CommandText.AppendLine("SELECT ..."); 48 | var result = cmd.ExecuteScalar(); 49 | 50 | Assert.AreEqual(0, result); 51 | } 52 | } 53 | 54 | [TestMethod] 55 | public void Mock_ContainsSql_NullableIntegerScalar_Null_Test() 56 | { 57 | // Issue #27 - https://github.com/Apps72/DbMocker/issues/27 58 | // https://docs.microsoft.com/en-us/dotnet/api/system.data.common.dbcommand.executescalar 59 | // If the first column of the first row in the result set is not found, a null reference is returned. 60 | 61 | var conn = new MockDbConnection(); 62 | 63 | conn.Mocks 64 | .When(c => c.CommandText.Contains("SELECT")) 65 | .ReturnsScalar((int?)null); 66 | 67 | using (var cmd = new DatabaseCommand(conn)) 68 | { 69 | cmd.CommandText.AppendLine("SELECT ..."); 70 | 71 | var result = cmd.ExecuteScalar(); 72 | 73 | Assert.AreEqual(null, result); 74 | } 75 | } 76 | 77 | [TestMethod] 78 | public void Mock_ContainsSql_NullableIntegerScalar_DbNull_Test() 79 | { 80 | // Issue #27 - https://github.com/Apps72/DbMocker/issues/27 81 | // https://docs.microsoft.com/en-us/dotnet/api/system.data.common.dbcommand.executescalar 82 | // If the value in the database is null, the query returns DBNull.Value. 83 | 84 | var conn = new MockDbConnection(); 85 | 86 | conn.Mocks 87 | .When(c => c.CommandText.Contains("SELECT")) 88 | .ReturnsScalar(DBNull.Value); 89 | 90 | using (var cmd = new DatabaseCommand(conn)) 91 | { 92 | cmd.CommandText.AppendLine("SELECT ..."); 93 | var result = cmd.ExecuteScalar(); 94 | 95 | Assert.AreEqual(DBNull.Value, result); 96 | } 97 | } 98 | 99 | [TestMethod] 100 | public void Mock_ContainsSql_IntegerScalar_DbNull_Test() 101 | { 102 | var conn = new MockDbConnection(); 103 | 104 | conn.Mocks 105 | .When(c => c.CommandText.Contains("SELECT")) 106 | .ReturnsScalar(System.DBNull.Value); 107 | 108 | using (var cmd = new DatabaseCommand(conn)) 109 | { 110 | cmd.CommandText.AppendLine("SELECT ..."); 111 | var result = cmd.ExecuteScalar(); 112 | 113 | Assert.AreEqual(0, result); 114 | } 115 | } 116 | 117 | [TestMethod] 118 | public void Mock_ContainsSql_StringScalar_DbNull_Test() 119 | { 120 | var conn = new MockDbConnection(); 121 | 122 | conn.Mocks 123 | .When(c => c.CommandText.Contains("SELECT")) 124 | .ReturnsScalar(System.DBNull.Value); 125 | 126 | using (var cmd = new DatabaseCommand(conn)) 127 | { 128 | cmd.CommandText.AppendLine("SELECT ..."); 129 | var result = cmd.ExecuteScalar(); 130 | 131 | Assert.AreEqual(null, result); 132 | } 133 | } 134 | 135 | [TestMethod] 136 | public void Mock_ContainsSql_StringScalar_Null_Test() 137 | { 138 | var conn = new MockDbConnection(); 139 | 140 | conn.Mocks 141 | .When(c => c.CommandText.Contains("SELECT")) 142 | .ReturnsScalar((string)null); 143 | 144 | using (var cmd = new DatabaseCommand(conn)) 145 | { 146 | cmd.CommandText.AppendLine("SELECT ..."); 147 | var result = cmd.ExecuteScalar(); 148 | 149 | Assert.AreEqual(null, result); 150 | } 151 | } 152 | 153 | [TestMethod] 154 | public void Mock_ContainsSql_And_Parameter_Test() 155 | { 156 | var conn = new MockDbConnection(); 157 | 158 | conn.Mocks 159 | .When(c => c.CommandText.Contains("SELECT") && 160 | c.Parameters.Any(p => p.ParameterName == "@ID")) 161 | .ReturnsScalar(14); 162 | 163 | using (var cmd = new DatabaseCommand(conn)) 164 | { 165 | cmd.CommandText.AppendLine("SELECT ..."); 166 | cmd.AddParameter("@ID", 1); 167 | var result = cmd.ExecuteScalar(); 168 | 169 | Assert.AreEqual(14, result); 170 | } 171 | } 172 | 173 | [TestMethod] 174 | public void Mock_ExecuteNonQuery_Test() 175 | { 176 | var conn = new MockDbConnection(); 177 | 178 | conn.Mocks 179 | .When(c => c.CommandText.Contains("INSERT")) 180 | .ReturnsScalar(14); 181 | 182 | using (var cmd = new DatabaseCommand(conn)) 183 | { 184 | cmd.CommandText.AppendLine("INSERT ..."); 185 | cmd.AddParameter("@ID", 1); 186 | var result = cmd.ExecuteNonQuery(); 187 | 188 | Assert.AreEqual(14, result); 189 | } 190 | } 191 | 192 | [TestMethod] 193 | public void Mock_ExecuteTable_Test() 194 | { 195 | var conn = new MockDbConnection(); 196 | 197 | conn.Mocks 198 | .When(null) 199 | .ReturnsTable(new MockTable() 200 | { 201 | Columns = Columns.WithNames("Col1", "Col2", "Col3"), 202 | Rows = new object[,] 203 | { 204 | { 0, 1, 2 }, 205 | { 9, 8, 7 }, 206 | { 4, 5, 6 }, 207 | } 208 | }); 209 | 210 | using (var cmd = new DatabaseCommand(conn)) 211 | { 212 | cmd.CommandText.AppendLine("SELECT ..."); 213 | var result = cmd.ExecuteTable(new 214 | { 215 | Col1 = 0, 216 | Col2 = 0, 217 | Col3 = 0 218 | }); 219 | 220 | Assert.AreEqual(3, result.Count()); // 3 rows 221 | Assert.AreEqual(1, result.First().Col2); // First row / Col2 222 | } 223 | 224 | } 225 | 226 | [TestMethod] 227 | public void Mock_ParameterOutput_Test() 228 | { 229 | var conn = new MockDbConnection(); 230 | 231 | conn.Mocks 232 | .When(c => c.CommandText.Contains("EXEC PROC")) 233 | .SetParameterValue("@OUT", "OutValue") 234 | .ReturnsScalar(777); 235 | 236 | var cmd = conn.CreateCommand(); 237 | cmd.CommandText = "EXEC PROC @out1 = @OUT"; 238 | 239 | var outParam = cmd.CreateParameter(); 240 | outParam.ParameterName = "@OUT"; 241 | outParam.Direction = System.Data.ParameterDirection.Output; 242 | cmd.Parameters.Add(outParam); 243 | 244 | var result = cmd.ExecuteScalar(); 245 | 246 | Assert.AreEqual("OutValue", outParam.Value); 247 | } 248 | 249 | [TestMethod] 250 | public void Mock_ExecuteTable_WithNullInFirstRow_Test() 251 | { 252 | var conn = new MockDbConnection(); 253 | 254 | conn.Mocks 255 | .When(null) 256 | .ReturnsTable(new MockTable() 257 | { 258 | Columns = Columns.WithNames("Col1", "Col2", "Col3"), 259 | Rows = new object[,] 260 | { 261 | { null, 1, 2 }, 262 | { null, 8, 7 }, 263 | { 4, 5, 6 }, 264 | } 265 | }); 266 | 267 | using (var cmd = new DatabaseCommand(conn)) 268 | { 269 | cmd.CommandText.AppendLine("SELECT ..."); 270 | var result = cmd.ExecuteTable(new 271 | { 272 | Col1 = (int?)0, 273 | Col2 = 0, 274 | Col3 = 0 275 | }); 276 | 277 | Assert.AreEqual(null, result.ElementAt(0).Col1); 278 | Assert.AreEqual(null, result.ElementAt(1).Col1); 279 | Assert.AreEqual(4, result.ElementAt(2).Col1); 280 | } 281 | 282 | } 283 | 284 | [TestMethod] 285 | public void Mock_ExecuteRow_WithTable_Test() 286 | { 287 | var conn = new MockDbConnection(); 288 | 289 | conn.Mocks 290 | .WhenAny() 291 | .ReturnsTable( 292 | MockTable.WithColumns("Col1", "Col2") 293 | .AddRow(10, 11) 294 | .AddRow(12, 13)); 295 | 296 | using (var cmd = new DatabaseCommand(conn)) 297 | { 298 | cmd.CommandText.AppendLine("SELECT ..."); 299 | var result = cmd.ExecuteRow(new 300 | { 301 | Col1 = default(int?), 302 | Col2 = default(int), 303 | }); 304 | 305 | Assert.AreEqual(10, result.Col1); 306 | Assert.AreEqual(11, result.Col2); 307 | } 308 | 309 | } 310 | 311 | [TestMethod] 312 | public void Mock_ExecuteScalar_WithTable_Test() 313 | { 314 | var conn = new MockDbConnection(); 315 | 316 | conn.Mocks 317 | .WhenAny() 318 | .ReturnsTable( 319 | new MockTable().AddColumns("Col1", "Col2") 320 | .AddRow(10, 11) 321 | .AddRow(12, 13)); 322 | 323 | using (var cmd = new DatabaseCommand(conn)) 324 | { 325 | cmd.CommandText.AppendLine("SELECT ..."); 326 | var result = cmd.ExecuteRow(); 327 | 328 | Assert.AreEqual(10, result); 329 | } 330 | 331 | } 332 | 333 | [TestMethod] 334 | public void Mock_FormatedCommandText_Test() 335 | { 336 | var conn = new MockDbConnection(); 337 | 338 | conn.Mocks 339 | .When(c => c.CommandText.Contains("SELECT")) 340 | .ReturnsScalar(14); 341 | 342 | using (var cmd = new DatabaseCommand(conn)) 343 | { 344 | cmd.CommandText = @"SELECT * 345 | FROM EMP 346 | WHERE ID = @Id 347 | AND ENAME = @Name 348 | AND HIREDATE = @HireDate"; 349 | 350 | cmd.AddParameter("@Id", 123); 351 | cmd.AddParameter("@Name", "Denis"); 352 | cmd.AddParameter("@HireDate", new DateTime(2019, 05, 03)); 353 | 354 | var formatedCommandAsText = cmd.Formatted.CommandAsText; 355 | var formatedCommandAsVariables = cmd.Formatted.CommandAsVariables; 356 | 357 | Assert.IsTrue(formatedCommandAsText.Contains("ID = 123")); 358 | Assert.IsTrue(formatedCommandAsText.Contains("ENAME = 'Denis'")); 359 | Assert.IsTrue(formatedCommandAsText.Contains("HIREDATE = '2019-05-03'")); 360 | 361 | Assert.IsTrue(formatedCommandAsVariables.Contains("DECLARE @Id AS INT = 123")); 362 | Assert.IsTrue(formatedCommandAsVariables.Contains("DECLARE @Name AS VARCHAR")); 363 | Assert.IsTrue(formatedCommandAsVariables.Contains("DECLARE @HireDate AS DATETIME = '2019-05-03'")); 364 | } 365 | } 366 | 367 | [TestMethod] 368 | public void Mock_ExecuteDataset_Test() 369 | { 370 | var conn = new MockDbConnection(); 371 | 372 | MockTable table1 = MockTable.WithColumns("Col1", "Col2") 373 | .AddRow(11, 12); 374 | 375 | MockTable table2 = MockTable.WithColumns("Col3", "Col4") 376 | .AddRow("MyString", 3.4); 377 | 378 | conn.Mocks 379 | .When(null) 380 | .ReturnsDataset(table1, table2); 381 | 382 | using (var cmd = new DatabaseCommand(conn)) 383 | { 384 | cmd.CommandText.AppendLine("SELECT ..."); 385 | var result = cmd.ExecuteDataSet(new { Col1 = 0, Col2 = 0 }, 386 | new { Col3 = "", Col4 = 0.0 }); 387 | 388 | Assert.AreEqual(1, result.Item1.Count()); // 1 row 389 | Assert.AreEqual(11, result.Item1.First().Col1); 390 | Assert.AreEqual(12, result.Item1.First().Col2); 391 | 392 | Assert.AreEqual(1, result.Item2.Count()); // 1 row 393 | Assert.AreEqual("MyString", result.Item2.First().Col3); 394 | Assert.AreEqual(3.4, result.Item2.First().Col4); 395 | } 396 | 397 | } 398 | 399 | [TestMethod] 400 | public void Mock_ExecuteDataset_WithFunction_Test() 401 | { 402 | var conn = new MockDbConnection(); 403 | 404 | MockTable table1 = MockTable.WithColumns("Col1", "Col2") 405 | .AddRow(11, 12); 406 | 407 | MockTable table2 = MockTable.WithColumns("Col3", "Col4") 408 | .AddRow("MyString", 3.4); 409 | 410 | conn.Mocks 411 | .When(null) 412 | .ReturnsDataset(cmd => new[] { table1, table2 }); 413 | 414 | using (var cmd = new DatabaseCommand(conn)) 415 | { 416 | cmd.CommandText.AppendLine("SELECT ..."); 417 | var result = cmd.ExecuteDataSet(new { Col1 = 0, Col2 = 0 }, 418 | new { Col3 = "", Col4 = 0.0 }); 419 | 420 | Assert.AreEqual(1, result.Item1.Count()); // 1 row 421 | Assert.AreEqual(11, result.Item1.First().Col1); 422 | Assert.AreEqual(12, result.Item1.First().Col2); 423 | 424 | Assert.AreEqual(1, result.Item2.Count()); // 1 row 425 | Assert.AreEqual("MyString", result.Item2.First().Col3); 426 | Assert.AreEqual(3.4, result.Item2.First().Col4); 427 | } 428 | 429 | } 430 | 431 | [TestMethod] 432 | public void Mock_ThrowException_Test() 433 | { 434 | var conn = new MockDbConnection(); 435 | 436 | conn.Mocks 437 | .WhenAny() 438 | .ThrowsException(new Exception("TestException")); 439 | 440 | using (var cmd = new DatabaseCommand(conn)) 441 | { 442 | var exception = Assert.ThrowsException(() => 443 | { 444 | cmd.CommandText.AppendLine("SELECT ..."); 445 | cmd.ExecuteScalar(); 446 | }); 447 | 448 | Assert.IsNotNull(exception); 449 | Assert.AreEqual("TestException", exception.Message); 450 | } 451 | } 452 | 453 | [TestMethod] 454 | public void Mock_ThrowGenericException_Test() 455 | { 456 | var conn = new MockDbConnection(); 457 | 458 | conn.Mocks 459 | .WhenAny() 460 | .ThrowsException(); 461 | 462 | using (var cmd = new DatabaseCommand(conn)) 463 | { 464 | var exception = Assert.ThrowsException(() => 465 | { 466 | cmd.CommandText.AppendLine("SELECT ..."); 467 | cmd.ExecuteScalar(); 468 | }); 469 | 470 | Assert.IsNotNull(exception); 471 | } 472 | } 473 | 474 | [DataRow(new int[] { 20 })] // 1 table with value in first row/cell = 20 475 | [DataRow(new int[] { 10, 20, 30 })] // 3 tables with value in first row/cell = 10, 20, 30 476 | [DataTestMethod()] 477 | public void Mock_MultipleDataReader_Test(int[] CellValues) 478 | { 479 | var conn = new MockDbConnection(); 480 | 481 | var tables = Enumerable.Range(0, CellValues.Length).Select(i => MockTable.WithColumns("Count").AddRow(CellValues[i])); 482 | 483 | conn.Mocks.WhenAny() 484 | .ReturnsDataset(tables.ToArray()); 485 | 486 | var count = GetCountValues(conn).ToArray(); 487 | 488 | Assert.AreEqual(CellValues.Length, count.Count()); 489 | Assert.AreEqual(CellValues.First(), count.First()); 490 | Assert.AreEqual(CellValues.Last(), count.Last()); 491 | 492 | // Returns a list with all Rows[0][0] values, for each tables. 493 | IEnumerable GetCountValues(DbConnection connection) 494 | { 495 | var result = new List(); 496 | var dataSet = new DataSet(); 497 | 498 | using var cmd = connection.CreateCommand(); 499 | cmd.CommandText = "SELECT ..."; 500 | 501 | using (var myReader = cmd.ExecuteReader()) 502 | { 503 | do 504 | { 505 | var dataTable = new DataTable(); 506 | dataTable.Load(myReader); 507 | dataSet.Tables.Add(dataTable); 508 | } 509 | while (myReader.IsClosed == false); 510 | } 511 | 512 | foreach (DataTable table in dataSet.Tables) 513 | { 514 | yield return Convert.ToInt32(table.Rows[0][0]); 515 | } 516 | } 517 | } 518 | } 519 | } 520 | -------------------------------------------------------------------------------- /DbMocker.Tests/DbMockCallbackTests.cs: -------------------------------------------------------------------------------- 1 | using Apps72.Dev.Data.DbMocker; 2 | 3 | using Microsoft.VisualStudio.TestTools.UnitTesting; 4 | 5 | using System.Data.Common; 6 | 7 | namespace DbMocker.Tests 8 | { 9 | [TestClass] 10 | public class DbMockCallbackTests 11 | { 12 | [TestMethod] 13 | public void Mock_CallsCallback_Single() 14 | { 15 | var counter = 0; 16 | 17 | MockDbConnection conn = new(); 18 | 19 | conn.Mocks 20 | .WhenAny() 21 | .Callback(_ => counter++) 22 | .ReturnsScalar(1); 23 | 24 | DbCommand cmd = conn.CreateCommand(); 25 | cmd.CommandText = "SELECT COUNT(*) FROM EMP"; 26 | 27 | var result1 = cmd.ExecuteScalar(); 28 | var result2 = cmd.ExecuteScalar()!; 29 | var result3 = cmd.ExecuteScalar()!; 30 | 31 | Assert.AreEqual(1, result1); 32 | Assert.AreEqual(1, result2); 33 | Assert.AreEqual(1, result3); 34 | 35 | Assert.AreEqual(3, counter); 36 | } 37 | 38 | [TestMethod] 39 | public void Mock_CallsCallback_Multiple() 40 | { 41 | var counter1 = 0; 42 | var counter2 = 0; 43 | 44 | MockDbConnection conn = new(); 45 | 46 | conn.Mocks 47 | .WhenAny() 48 | .Callback(_ => counter1++) 49 | .Callback(_ => counter2++) 50 | .ReturnsScalar(1); 51 | 52 | DbCommand cmd = conn.CreateCommand(); 53 | cmd.CommandText = "SELECT COUNT(*) FROM EMP"; 54 | 55 | var result1 = cmd.ExecuteScalar(); 56 | 57 | Assert.AreEqual(1, counter1); 58 | Assert.AreEqual(1, counter2); 59 | } 60 | } 61 | } 62 | -------------------------------------------------------------------------------- /DbMocker.Tests/DbMockDatasetTests.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Data; 3 | using System.Data.Common; 4 | using System.Diagnostics; 5 | using System.Linq; 6 | using Apps72.Dev.Data.DbMocker; 7 | using Apps72.Dev.Data.DbMocker.Helpers; 8 | using Microsoft.VisualStudio.TestTools.UnitTesting; 9 | 10 | namespace DbMocker.Tests 11 | { 12 | [TestClass] 13 | public class DbMockDatasetTests 14 | { 15 | [TestMethod] 16 | public void Mock_Dataset_MultipleTables_Test() 17 | { 18 | var traced = false; 19 | var conn = new MockDbConnection(); 20 | 21 | MockTable table1 = MockTable.WithColumns("Col1", "Col2") 22 | .AddRow(11, 12); 23 | 24 | MockTable table2 = MockTable.WithColumns("Col3", "Col4") 25 | .AddRow("MyString", 3.4); 26 | 27 | conn.Mocks 28 | .WhenAny() 29 | .Callback(_ => { traced = true; }) 30 | .ReturnsDataset(table1, table2); 31 | 32 | // First DataTable 33 | DbCommand cmd = conn.CreateCommand(); 34 | DbDataReader result = cmd.ExecuteReader(); 35 | 36 | Assert.IsTrue(result.Read()); 37 | 38 | Assert.IsTrue(traced); 39 | Assert.AreEqual(11, result.GetInt32(0)); 40 | Assert.AreEqual(12, result.GetInt32(1)); 41 | 42 | // Second DataTable 43 | Assert.IsTrue(result.NextResult()); 44 | Assert.IsTrue(result.Read()); 45 | 46 | Assert.AreEqual("MyString", result.GetString(0)); 47 | Assert.AreEqual(3.4, result.GetDouble(1)); 48 | } 49 | 50 | [TestMethod] 51 | public void Mock_Dataset_NoTable_Test() 52 | { 53 | var conn = new MockDbConnection(); 54 | 55 | conn.Mocks 56 | .WhenAny() 57 | .ReturnsDataset(); 58 | 59 | // First DataTable 60 | DbCommand cmd = conn.CreateCommand(); 61 | DbDataReader result = cmd.ExecuteReader(); 62 | 63 | Assert.IsFalse(result.Read()); 64 | Assert.AreEqual(null, result.GetValue(0)); 65 | } 66 | 67 | [TestMethod] 68 | public void Mock_Dataset_Func_Test() 69 | { 70 | var conn = new MockDbConnection(); 71 | 72 | MockTable table1 = MockTable.WithColumns("Col1", "Col2") 73 | .AddRow(11, 12); 74 | 75 | MockTable table2 = MockTable.WithColumns("Col3", "Col4") 76 | .AddRow("MyString", 3.4); 77 | 78 | conn.Mocks 79 | .WhenAny() 80 | .ReturnsDataset(mockCmd => 81 | { 82 | Assert.AreEqual("SELECT ...", mockCmd.CommandText); 83 | return new MockTable[] { table1, table2 }; 84 | }); 85 | 86 | // First DataTable 87 | DbCommand cmd = conn.CreateCommand(); 88 | cmd.CommandText = "SELECT ..."; 89 | DbDataReader result = cmd.ExecuteReader(); 90 | 91 | Assert.IsTrue(result.Read()); 92 | 93 | Assert.AreEqual(11, result.GetInt32(0)); 94 | Assert.AreEqual(12, result.GetInt32(1)); 95 | 96 | // Second DataTable 97 | Assert.IsTrue(result.NextResult()); 98 | Assert.IsTrue(result.Read()); 99 | 100 | Assert.AreEqual("MyString", result.GetString(0)); 101 | Assert.AreEqual(3.4, result.GetDouble(1)); 102 | } 103 | 104 | [TestMethod] 105 | public void Mock_Dataset_MultipleTables_Load_DataSet_Test() 106 | { 107 | var conn = new MockDbConnection(); 108 | 109 | MockTable table1 = MockTable.WithColumns("Col1", "Col2") 110 | .AddRow(11, 12); 111 | 112 | MockTable table2 = MockTable.WithColumns("Col3", "Col4") 113 | .AddRow("MyString", 3.4); 114 | 115 | conn.Mocks 116 | .WhenAny() 117 | .ReturnsDataset(table1, table2); 118 | 119 | // First DataTable 120 | DbCommand cmd = conn.CreateCommand(); 121 | DbDataReader result = cmd.ExecuteReader(); 122 | 123 | DataSet dataSet = new DataSet(); 124 | 125 | dataSet.Load(result, LoadOption.OverwriteChanges, "table1", "table2"); 126 | 127 | Assert.AreEqual(2, dataSet.Tables.Count); 128 | 129 | // First DataTable 130 | Assert.AreEqual(1, dataSet.Tables["table1"].Rows.Count); 131 | Assert.AreEqual(2, dataSet.Tables["table1"].Columns.Count); 132 | Assert.AreEqual(11, (int)dataSet.Tables["table1"].Rows[0]["Col1"]); 133 | Assert.AreEqual(12, (int)dataSet.Tables["table1"].Rows[0]["Col2"]); 134 | 135 | //// Second DataTable 136 | Assert.AreEqual(1, dataSet.Tables["table2"].Rows.Count); 137 | Assert.AreEqual(2, dataSet.Tables["table2"].Columns.Count); 138 | Assert.AreEqual("MyString", (string)dataSet.Tables["table2"].Rows[0]["Col3"]); 139 | Assert.AreEqual(3.4, dataSet.Tables["table2"].Rows[0]["Col4"]); 140 | } 141 | } 142 | } 143 | -------------------------------------------------------------------------------- /DbMocker.Tests/DbMockResourceTests.cs: -------------------------------------------------------------------------------- 1 | using Apps72.Dev.Data.DbMocker; 2 | using Microsoft.VisualStudio.TestTools.UnitTesting; 3 | using System; 4 | using System.Linq; 5 | using System.Reflection; 6 | 7 | namespace DbMocker.Tests 8 | { 9 | [TestClass] 10 | public class DbMockResourceTests 11 | { 12 | [TestMethod] 13 | public void MockTable_FixedColumns_NormalTypes_Test() 14 | { 15 | string content = "Col1 Col2 Col3 \n" + 16 | "String Int32 (int) "; 17 | 18 | var table = MockTable.FromFixed(content); 19 | 20 | Assert.AreEqual(3, table.Columns.Length); 21 | Assert.AreEqual("Col1", table.Columns[0].Name); 22 | Assert.AreEqual("Col2", table.Columns[1].Name); 23 | Assert.AreEqual("Col3", table.Columns[2].Name); 24 | Assert.AreEqual(typeof(string), table.Columns[0].Type); 25 | Assert.AreEqual(typeof(int), table.Columns[1].Type); 26 | Assert.AreEqual(typeof(int), table.Columns[2].Type); 27 | } 28 | 29 | [TestMethod] 30 | public void MockTable_FixedColumns_MissingType_Test() 31 | { 32 | string content = "Col1 Col2 \n" + 33 | "(int)"; 34 | 35 | var table = MockTable.FromFixed(content); 36 | 37 | Assert.AreEqual(2, table.Columns.Length); 38 | Assert.AreEqual("Col1", table.Columns[0].Name); 39 | Assert.AreEqual("Col2", table.Columns[1].Name); 40 | Assert.AreEqual(typeof(int), table.Columns[0].Type); 41 | Assert.AreEqual(null, table.Columns[1].Type); 42 | } 43 | 44 | [TestMethod] 45 | public void MockTable_Int32_Test() 46 | { 47 | string content = "Col1 \n" + 48 | "(int) \n" + 49 | "123 "; 50 | 51 | var table = MockTable.FromFixed(content); 52 | 53 | Assert.AreEqual(typeof(int), table.Columns[0].Type); 54 | Assert.AreEqual(123, table.Rows[0, 0]); 55 | } 56 | 57 | [TestMethod] 58 | public void MockTable_Decimal_Test() 59 | { 60 | string content = "Col1 \n" + 61 | "(decimal) \n" + 62 | "123.45 "; 63 | 64 | var table = MockTable.FromFixed(content); 65 | 66 | Assert.AreEqual(typeof(decimal), table.Columns[0].Type); 67 | Assert.AreEqual((decimal)123.45, table.Rows[0, 0]); 68 | } 69 | 70 | [TestMethod] 71 | public void MockTable_TimeSpan_Test() 72 | { 73 | string content = "Col1 \n" + 74 | "(timespan) \n" + 75 | "01:02:03.123 "; 76 | 77 | var table = MockTable.FromFixed(content); 78 | 79 | Assert.AreEqual(typeof(TimeSpan), table.Columns[0].Type); 80 | Assert.AreEqual(new TimeSpan(0,1,2,3,123), table.Rows[0,0]); 81 | } 82 | 83 | [TestMethod] 84 | public void MockTable_DateTime_Test() 85 | { 86 | string content = "Col1 \n" + 87 | "(date) \n" + 88 | "2020-01-15 "; 89 | 90 | var table = MockTable.FromFixed(content); 91 | 92 | Assert.AreEqual(typeof(DateTime), table.Columns[0].Type); 93 | Assert.AreEqual(new DateTime(2020, 01, 15), table.Rows[0, 0]); 94 | } 95 | 96 | [TestMethod] 97 | [ExpectedException(typeof(InvalidCastException))] 98 | public void MockTable_InvalidDate_Test() 99 | { 100 | string content = "Col1 \n" + 101 | "(date) \n" + 102 | "2020-01-32 "; 103 | 104 | var table = MockTable.FromFixed(content); 105 | } 106 | 107 | [TestMethod] 108 | public void MockTable_Boolean_Test() 109 | { 110 | string content = "Col1 \n" + 111 | "(bool) \n" + 112 | "true "; 113 | 114 | var table = MockTable.FromFixed(content); 115 | 116 | Assert.AreEqual(typeof(Boolean), table.Columns[0].Type); 117 | Assert.AreEqual(true, table.Rows[0, 0]); 118 | } 119 | 120 | [TestMethod] 121 | public void MockTable_String_Test() 122 | { 123 | string content = "Col1 \n" + 124 | "(string) \n" + 125 | "ABC "; 126 | 127 | var table = MockTable.FromFixed(content); 128 | 129 | Assert.AreEqual(typeof(String), table.Columns[0].Type); 130 | Assert.AreEqual("ABC", table.Rows[0, 0]); 131 | } 132 | 133 | [TestMethod] 134 | public void MockTable_StringGuillemets_Test() 135 | { 136 | string content = "Col1 \n" + 137 | "(string) \n" + 138 | "\"ABC DEF\" "; 139 | 140 | var table = MockTable.FromFixed(content); 141 | 142 | Assert.AreEqual(typeof(String), table.Columns[0].Type); 143 | Assert.AreEqual("ABC DEF", table.Rows[0, 0]); 144 | } 145 | 146 | [TestMethod] 147 | public void MockTable_Guid_Test() 148 | { 149 | string content = "Col1 \n" + 150 | "(guid) \n" + 151 | "b5acc392-3b9d-4059-9851-3d7344db6e91 "; 152 | 153 | var table = MockTable.FromFixed(content); 154 | 155 | Assert.AreEqual(typeof(Guid), table.Columns[0].Type); 156 | Assert.AreEqual(new Guid("b5acc392-3b9d-4059-9851-3d7344db6e91"), table.Rows[0, 0]); 157 | } 158 | 159 | [TestMethod] 160 | [ExpectedException(typeof(InvalidCastException))] 161 | public void MockTable_InvalidGuid_Test() 162 | { 163 | string content = "Col1 \n" + 164 | "(guid) \n" + 165 | "b5acc392-XXXX-XXXX-XXXX-3d7344db6e91 "; 166 | 167 | var table = MockTable.FromFixed(content); 168 | } 169 | 170 | [TestMethod] 171 | public void MockTable_FixedColumns_MissingColumn_Test() 172 | { 173 | string content = "Col1 \n" + 174 | "int string"; 175 | 176 | var table = MockTable.FromFixed(content); 177 | 178 | Assert.AreEqual(1, table.Columns.Length); 179 | Assert.AreEqual("Col1", table.Columns[0].Name); 180 | Assert.AreEqual(null, table.Columns[0].Type); 181 | } 182 | 183 | [TestMethod] 184 | public void MockTable_FixedColumns_Values_Test() 185 | { 186 | string content = "Col1 Col2 \n" + 187 | "string int \n" + 188 | "ABC 0 \n" + 189 | "DEF 314 \n" + 190 | "GHI NULL "; 191 | 192 | var table = MockTable.FromFixed(content); 193 | 194 | Assert.AreEqual("ABC", table.Rows[0, 0]); 195 | Assert.AreEqual(0, table.Rows[0, 1]); 196 | 197 | Assert.AreEqual("DEF", table.Rows[1, 0]); 198 | Assert.AreEqual(314, table.Rows[1, 1]); 199 | 200 | Assert.AreEqual("GHI", table.Rows[2, 0]); 201 | Assert.AreEqual(null, table.Rows[2, 1]); 202 | } 203 | 204 | [TestMethod] 205 | public void MockTable_FixedColumns_Date_Test() 206 | { 207 | string content = "Col1 Col2 \n" + 208 | "DateTime int \n" + 209 | "2020-01-05 99 \n" + 210 | "NULL 88 "; 211 | 212 | var table = MockTable.FromFixed(content); 213 | 214 | Assert.AreEqual(new DateTime(2020, 1, 5), table.Rows[0, 0]); 215 | Assert.AreEqual(99, table.Rows[0, 1]); 216 | 217 | Assert.AreEqual(null, table.Rows[1, 0]); 218 | Assert.AreEqual(88, table.Rows[1, 1]); 219 | } 220 | 221 | [TestMethod] 222 | public void MockTable_FixedColumns_String_Test() 223 | { 224 | string content = "Col1 Col2 \n" + 225 | "string int \n" + 226 | "abc def 99 "; 227 | 228 | var table = MockTable.FromFixed(content); 229 | 230 | Assert.AreEqual("abc def", table.Rows[0, 0]); 231 | Assert.AreEqual(99, table.Rows[0, 1]); 232 | } 233 | 234 | [TestMethod] 235 | public void MockTable_FixedColumns_StringGuillemets_Test() 236 | { 237 | string content = "Col1 Col2 \n" + 238 | "string int \n" + 239 | "\" abc def \" "; 240 | 241 | var table = MockTable.FromFixed(content); 242 | 243 | Assert.AreEqual(" abc def ", table.Rows[0, 0]); 244 | Assert.AreEqual(null, table.Rows[0, 1]); 245 | } 246 | 247 | [TestMethod] 248 | public void MockTable_FixedColumns_FromResourceSample1_Test() 249 | { 250 | var table = MockTable.FromFixed(Assembly.GetExecutingAssembly(), "DbMocker.Tests.Samples.SampleTable1.txt"); 251 | 252 | Assert.AreEqual(4, table.Columns.Length); 253 | 254 | Assert.AreEqual("Id", table.Columns[0].Name); 255 | Assert.AreEqual("Name", table.Columns[1].Name); 256 | Assert.AreEqual("Age", table.Columns[2].Name); 257 | Assert.AreEqual("Male", table.Columns[3].Name); 258 | 259 | Assert.AreEqual(1, table.Rows[0, 0]); 260 | Assert.AreEqual("Denis", table.Rows[0, 1]); 261 | Assert.AreEqual(21, table.Rows[0, 2]); 262 | Assert.AreEqual(true, table.Rows[0, 3]); 263 | } 264 | 265 | [TestMethod] 266 | public void MockTable_Tags_FromAssemblyResources_Test() 267 | { 268 | var conn = new MockDbConnection(); 269 | conn.Mocks.LoadTagsFromResources(Assembly.GetExecutingAssembly(), 270 | "SampleTable1", "SAMPLETABLE2"); 271 | 272 | Assert.AreEqual(2, conn.Mocks.Conditions.Count()); 273 | 274 | // SampleTable1 275 | var cmd1 = conn.CreateCommand(); 276 | cmd1.CommandText = @"-- SampleTable1 277 | SELECT ... "; 278 | var result1 = cmd1.ExecuteScalar(); 279 | 280 | Assert.AreEqual(1, result1); 281 | 282 | // SampleTable2 283 | var cmd2 = conn.CreateCommand(); 284 | cmd2.CommandText = @"-- SAMPLETABLE2 285 | SELECT ... "; 286 | var result2 = cmd2.ExecuteScalar(); 287 | 288 | Assert.AreEqual(123, result2); 289 | } 290 | 291 | [TestMethod] 292 | public void MockTable_Tags_FromCurrentResources_Test() 293 | { 294 | var conn = new MockDbConnection(); 295 | conn.Mocks.LoadTagsFromResources("SampleTable1", "SAMPLETABLE2"); 296 | 297 | Assert.AreEqual(2, conn.Mocks.Conditions.Count()); 298 | } 299 | 300 | [TestMethod] 301 | public void MockTable_Tags_SplitTags_Test() 302 | { 303 | var conn = new MockDbConnection(); 304 | conn.Mocks.LoadTagsFromResources("XX-SampleTable1"); 305 | 306 | // SampleTable1 307 | var cmd1 = conn.CreateCommand(); 308 | cmd1.CommandText = @"-- SampleTable1 309 | SELECT ... "; 310 | var result1 = cmd1.ExecuteScalar(); 311 | 312 | Assert.AreEqual(10, result1); 313 | } 314 | } 315 | } 316 | -------------------------------------------------------------------------------- /DbMocker.Tests/DbMockSqlParserTests.cs: -------------------------------------------------------------------------------- 1 | using Apps72.Dev.Data; 2 | using Apps72.Dev.Data.DbMocker; 3 | using Microsoft.VisualStudio.TestTools.UnitTesting; 4 | using System; 5 | using System.Data.SqlClient; 6 | using System.Linq; 7 | using System.Text; 8 | 9 | namespace DbMocker.Tests 10 | { 11 | [TestClass] 12 | public class DbMockSqlParserTests 13 | { 14 | [TestMethod] 15 | public void Mock_SqlParser_Validate_When_Test() 16 | { 17 | var conn = new MockDbConnection(); 18 | 19 | conn.Mocks 20 | .When(c => c.HasValidSqlServerCommandText()) 21 | .ReturnsScalar(99); 22 | 23 | var cmd = conn.CreateCommand(); 24 | cmd.CommandText = @"DECLARE @MyVar AS INT; 25 | SELECT * FROM EMP WHERE EMPNO = @MyVar;"; 26 | var result = cmd.ExecuteScalar(); 27 | 28 | Assert.AreEqual(99, result); 29 | } 30 | 31 | [TestMethod] 32 | public void Mock_SqlParser_Validate_WhenAny_Test() 33 | { 34 | var conn = new MockDbConnection(); 35 | 36 | conn.Mocks 37 | .HasValidSqlServerCommandText() 38 | .WhenAny() 39 | .ReturnsScalar(99); 40 | 41 | var cmd = conn.CreateCommand(); 42 | cmd.CommandText = @"DECLARE @MyVar AS INT; 43 | SELECT * FROM EMP WHERE EMPNO = @MyVar;"; 44 | var result = cmd.ExecuteScalar(); 45 | 46 | Assert.AreEqual(99, result); 47 | } 48 | 49 | [TestMethod] 50 | public void Mock_SqlParser_Validate_WhenTag_Test() 51 | { 52 | var conn = new MockDbConnection(); 53 | 54 | conn.Mocks 55 | .HasValidSqlServerCommandText() 56 | .WhenTag("MyTag") 57 | .ReturnsScalar(99); 58 | 59 | var cmd = conn.CreateCommand(); 60 | cmd.CommandText = @"-- MyTag 61 | SELECT * FROM EMP"; 62 | var result = cmd.ExecuteScalar(); 63 | 64 | Assert.AreEqual(99, result); 65 | } 66 | 67 | [TestMethod] 68 | public void Mock_SqlParser_Invalid_When_Test() 69 | { 70 | var conn = new MockDbConnection(); 71 | 72 | conn.Mocks 73 | .When(c => c.HasValidSqlServerCommandText()) 74 | .ReturnsScalar(99); 75 | 76 | var cmd = conn.CreateCommand(); 77 | cmd.CommandText = @"SELECT ** FROM EMP"; 78 | 79 | try 80 | { 81 | var result = cmd.ExecuteScalar(); 82 | Assert.Fail(); 83 | } 84 | catch (MockException ex) 85 | { 86 | Assert.IsInstanceOfType(ex, typeof(MockException)); 87 | Assert.IsTrue(ex.InnerException.Message.Contains("Incorrect syntax near '*'")); 88 | } 89 | } 90 | 91 | [TestMethod] 92 | public void Mock_SqlParser_Invalid_HasNextWhen_Test() 93 | { 94 | var conn = new MockDbConnection(); 95 | 96 | conn.Mocks 97 | .HasValidSqlServerCommandText() 98 | .When(c => c.CommandText.Contains("FROM EMP")) 99 | .ReturnsScalar(99); 100 | 101 | var cmd = conn.CreateCommand(); 102 | cmd.CommandText = @"SELECT ** FROM EMP"; 103 | 104 | try 105 | { 106 | var result = cmd.ExecuteScalar(); 107 | Assert.Fail(); 108 | } 109 | catch (MockException ex) 110 | { 111 | Assert.IsInstanceOfType(ex, typeof(MockException)); 112 | Assert.IsTrue(ex.InnerException.Message.Contains("Incorrect syntax near '*'")); 113 | } 114 | } 115 | 116 | [TestMethod] 117 | public void Mock_SqlParser_Invalid_WhenTag_Test() 118 | { 119 | var conn = new MockDbConnection(); 120 | 121 | conn.Mocks 122 | .HasValidSqlServerCommandText() 123 | .WhenTag("MyTag") 124 | .ReturnsScalar(99); 125 | 126 | var cmd = conn.CreateCommand(); 127 | cmd.CommandText = @"-- MyTag 128 | SELECT ** FROM EMP"; 129 | 130 | try 131 | { 132 | var result = cmd.ExecuteScalar(); 133 | Assert.Fail(); 134 | } 135 | catch (MockException ex) 136 | { 137 | Assert.IsInstanceOfType(ex, typeof(MockException)); 138 | Assert.IsTrue(ex.InnerException.Message.Contains("Incorrect syntax near '*'")); 139 | } 140 | } 141 | 142 | 143 | [TestMethod] 144 | public void Mock_SqlParser_Invalid_WhenAny_Test() 145 | { 146 | var conn = new MockDbConnection(); 147 | 148 | conn.Mocks 149 | .HasValidSqlServerCommandText() 150 | .WhenAny() 151 | .ReturnsScalar(99); 152 | 153 | var cmd = conn.CreateCommand(); 154 | cmd.CommandText = @"-- MyTag 155 | SELECT ** FROM EMP"; 156 | 157 | try 158 | { 159 | var result = cmd.ExecuteScalar(); 160 | Assert.Fail(); 161 | } 162 | catch (MockException ex) 163 | { 164 | Assert.IsInstanceOfType(ex, typeof(MockException)); 165 | Assert.IsTrue(ex.InnerException.Message.Contains("Incorrect syntax near '*'")); 166 | } 167 | } 168 | 169 | [TestMethod] 170 | public void Mock_SqlParser_TwoMock_OneValidate_Test() 171 | { 172 | var conn = new MockDbConnection(); 173 | 174 | conn.Mocks 175 | .When(c => c.CommandText.Contains("FROM EMP")) 176 | .ReturnsScalar(99); 177 | 178 | conn.Mocks 179 | .When(c => c.CommandText.Contains("FROM DEPT") && 180 | c.HasValidSqlServerCommandText()) 181 | .ReturnsScalar(99); 182 | 183 | // Command NON validated 184 | var cmd1 = conn.CreateCommand(); 185 | cmd1.CommandText = @"SELECT ** FROM EMP"; 186 | var result1 = cmd1.ExecuteScalar(); 187 | Assert.AreEqual(99, result1); 188 | 189 | // Command validated 190 | var cmd2 = conn.CreateCommand(); 191 | cmd2.CommandText = @"SELECT ** FROM DEPT"; 192 | 193 | try 194 | { 195 | var result = cmd2.ExecuteScalar(); 196 | Assert.Fail(); 197 | } 198 | catch (MockException ex) 199 | { 200 | Assert.IsInstanceOfType(ex, typeof(MockException)); 201 | Assert.IsTrue(ex.InnerException.Message.Contains("Incorrect syntax near '*'")); 202 | } 203 | } 204 | 205 | [TestMethod] 206 | public void Mock_SqlParser_GlobalHas_Test() 207 | { 208 | var conn = new MockDbConnection() 209 | { 210 | HasValidSqlServerCommandText = true 211 | }; 212 | 213 | conn.Mocks 214 | .When(c => c.CommandText.Contains("FROM EMP")) 215 | .ReturnsScalar(99); 216 | 217 | var cmd = conn.CreateCommand(); 218 | cmd.CommandText = @"SELECT ** FROM EMP"; 219 | 220 | try 221 | { 222 | var result = cmd.ExecuteScalar(); 223 | Assert.Fail(); 224 | } 225 | catch (MockException ex) 226 | { 227 | Assert.IsTrue(conn.HasValidSqlServerCommandText); 228 | Assert.IsInstanceOfType(ex, typeof(MockException)); 229 | Assert.IsTrue(ex.InnerException.Message.Contains("Incorrect syntax near '*'")); 230 | } 231 | } 232 | } 233 | } 234 | -------------------------------------------------------------------------------- /DbMocker.Tests/DbMockTableFromTypeTests.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using Apps72.Dev.Data.DbMocker; 3 | using DbMocker.Tests.SampleTypes; 4 | using Microsoft.VisualStudio.TestTools.UnitTesting; 5 | using System.Linq; 6 | using System.Reflection; 7 | using Microsoft.EntityFrameworkCore; 8 | 9 | namespace DbMocker.Tests 10 | { 11 | [TestClass] 12 | public class DbMockTableFromTypeTests 13 | { 14 | [TestMethod] 15 | public void Mock_MockTable_FromType_Test() 16 | { 17 | // Act 18 | var table = MockTable.FromType(); 19 | 20 | // Assert 21 | Assert.IsNotNull(table); 22 | 23 | Assert.AreEqual(7, table.Columns.Length); 24 | 25 | Assert.AreEqual(nameof(SimpleModel.Id), table.Columns[0].Name); 26 | Assert.AreEqual(nameof(SimpleModel.Name), table.Columns[1].Name); 27 | Assert.AreEqual(nameof(SimpleModel.Description), table.Columns[2].Name); 28 | Assert.AreEqual(nameof(SimpleModel.Value), table.Columns[3].Name); 29 | Assert.AreEqual(nameof(SimpleModel.Checksum), table.Columns[4].Name); 30 | Assert.AreEqual(nameof(SimpleModel.TimestampCreated), table.Columns[5].Name); 31 | Assert.AreEqual(nameof(SimpleModel.TimestampModified), table.Columns[6].Name); 32 | 33 | Assert.AreEqual(typeof(Guid), table.Columns[0].Type); 34 | Assert.AreEqual(typeof(string), table.Columns[1].Type); 35 | Assert.AreEqual(typeof(string), table.Columns[2].Type); 36 | Assert.AreEqual(typeof(int), table.Columns[3].Type); 37 | Assert.AreEqual(typeof(long?), table.Columns[4].Type); 38 | Assert.AreEqual(typeof(DateTime), table.Columns[5].Type); 39 | Assert.AreEqual(typeof(DateTime?), table.Columns[6].Type); 40 | } 41 | 42 | [TestMethod] 43 | public void Mock_MockTable_FromType_with_BindingFlags_override_Test() 44 | { 45 | // Arrange 46 | var bindingFlags = MockTable.DefaultFromTypeBindingFlags | BindingFlags.Static; 47 | 48 | // Act 49 | var table = MockTable.FromType(propertyBindingFlags: bindingFlags); 50 | 51 | // Assert 52 | Assert.IsNotNull(table); 53 | 54 | Assert.AreEqual(8, table.Columns.Length); 55 | 56 | Assert.AreEqual(nameof(SimpleModel.Id), table.Columns[0].Name); 57 | Assert.AreEqual(nameof(SimpleModel.Name), table.Columns[1].Name); 58 | Assert.AreEqual(nameof(SimpleModel.Description), table.Columns[2].Name); 59 | Assert.AreEqual(nameof(SimpleModel.Value), table.Columns[3].Name); 60 | Assert.AreEqual(nameof(SimpleModel.Checksum), table.Columns[4].Name); 61 | Assert.AreEqual(nameof(SimpleModel.TimestampCreated), table.Columns[5].Name); 62 | Assert.AreEqual(nameof(SimpleModel.TimestampModified), table.Columns[6].Name); 63 | 64 | Assert.AreEqual(typeof(Guid), table.Columns[0].Type); 65 | Assert.AreEqual(typeof(string), table.Columns[1].Type); 66 | Assert.AreEqual(typeof(string), table.Columns[2].Type); 67 | Assert.AreEqual(typeof(int), table.Columns[3].Type); 68 | Assert.AreEqual(typeof(long?), table.Columns[4].Type); 69 | Assert.AreEqual(typeof(DateTime), table.Columns[5].Type); 70 | Assert.AreEqual(typeof(DateTime?), table.Columns[6].Type); 71 | } 72 | 73 | [TestMethod] 74 | public void Mock_MockTable_FromType_with_RowData_Test() 75 | { 76 | // Arrange 77 | var rowData = Enumerable.Range(1, 5) 78 | .Select(x => 79 | { 80 | var instance = SimpleModel.RandomInstance(); 81 | if (x % 2 == 0) instance.CalculateChecksum(); 82 | if (x % 3 == 0) instance.SetUpdated(); 83 | return instance; 84 | }) 85 | .ToArray(); 86 | 87 | // Act 88 | var table = MockTable.FromType(rowData); 89 | 90 | // Assert 91 | Assert.IsNotNull(table); 92 | 93 | Assert.AreEqual(7, table.Columns.Length); 94 | 95 | Assert.AreEqual(nameof(SimpleModel.Id), table.Columns[0].Name); 96 | Assert.AreEqual(nameof(SimpleModel.Name), table.Columns[1].Name); 97 | Assert.AreEqual(nameof(SimpleModel.Description), table.Columns[2].Name); 98 | Assert.AreEqual(nameof(SimpleModel.Value), table.Columns[3].Name); 99 | Assert.AreEqual(nameof(SimpleModel.Checksum), table.Columns[4].Name); 100 | Assert.AreEqual(nameof(SimpleModel.TimestampCreated), table.Columns[5].Name); 101 | Assert.AreEqual(nameof(SimpleModel.TimestampModified), table.Columns[6].Name); 102 | 103 | Assert.AreEqual(typeof(Guid), table.Columns[0].Type); 104 | Assert.AreEqual(typeof(string), table.Columns[1].Type); 105 | Assert.AreEqual(typeof(string), table.Columns[2].Type); 106 | Assert.AreEqual(typeof(int), table.Columns[3].Type); 107 | Assert.AreEqual(typeof(long?), table.Columns[4].Type); 108 | Assert.AreEqual(typeof(DateTime), table.Columns[5].Type); 109 | Assert.AreEqual(typeof(DateTime?), table.Columns[6].Type); 110 | 111 | for (var i = 0; i < rowData.Length; ++i) 112 | { 113 | Assert.AreEqual(rowData[i].Id, table.Rows[i, 0]); 114 | Assert.AreEqual(rowData[i].Name, table.Rows[i, 1]); 115 | Assert.AreEqual(rowData[i].Description, table.Rows[i, 2]); 116 | Assert.AreEqual(rowData[i].Value, table.Rows[i, 3]); 117 | Assert.AreEqual(rowData[i].Checksum, table.Rows[i, 4]); 118 | Assert.AreEqual(rowData[i].TimestampCreated, table.Rows[i, 5]); 119 | Assert.AreEqual(rowData[i].TimestampModified, table.Rows[i, 6]); 120 | } 121 | } 122 | 123 | [TestMethod] 124 | public void Mock_MockTable_FromType_with_BindingFlags_override_and_RowData_Test() 125 | { 126 | // Arrange 127 | var bindingFlags = MockTable.DefaultFromTypeBindingFlags | BindingFlags.Static; 128 | 129 | var rowData = Enumerable.Range(1, 5) 130 | .Select(x => 131 | { 132 | var instance = SimpleModel.RandomInstance(); 133 | if (x % 2 == 0) instance.CalculateChecksum(); 134 | if (x % 3 == 0) instance.SetUpdated(); 135 | return instance; 136 | }) 137 | .ToArray(); 138 | 139 | // Act 140 | var table = MockTable.FromType(rowData, bindingFlags); 141 | 142 | // Assert 143 | Assert.IsNotNull(table); 144 | 145 | Assert.AreEqual(8, table.Columns.Length); 146 | 147 | Assert.AreEqual(nameof(SimpleModel.Id), table.Columns[0].Name); 148 | Assert.AreEqual(nameof(SimpleModel.Name), table.Columns[1].Name); 149 | Assert.AreEqual(nameof(SimpleModel.Description), table.Columns[2].Name); 150 | Assert.AreEqual(nameof(SimpleModel.Value), table.Columns[3].Name); 151 | Assert.AreEqual(nameof(SimpleModel.Checksum), table.Columns[4].Name); 152 | Assert.AreEqual(nameof(SimpleModel.TimestampCreated), table.Columns[5].Name); 153 | Assert.AreEqual(nameof(SimpleModel.TimestampModified), table.Columns[6].Name); 154 | Assert.AreEqual(nameof(SimpleModel.RandomValue), table.Columns[7].Name); 155 | 156 | Assert.AreEqual(typeof(Guid), table.Columns[0].Type); 157 | Assert.AreEqual(typeof(string), table.Columns[1].Type); 158 | Assert.AreEqual(typeof(string), table.Columns[2].Type); 159 | Assert.AreEqual(typeof(int), table.Columns[3].Type); 160 | Assert.AreEqual(typeof(long?), table.Columns[4].Type); 161 | Assert.AreEqual(typeof(DateTime), table.Columns[5].Type); 162 | Assert.AreEqual(typeof(DateTime?), table.Columns[6].Type); 163 | Assert.AreEqual(typeof(long), table.Columns[7].Type); 164 | 165 | for (var i = 0; i < rowData.Length; ++i) 166 | { 167 | Assert.AreEqual(rowData[i].Id, table.Rows[i, 0]); 168 | Assert.AreEqual(rowData[i].Name, table.Rows[i, 1]); 169 | Assert.AreEqual(rowData[i].Description, table.Rows[i, 2]); 170 | Assert.AreEqual(rowData[i].Value, table.Rows[i, 3]); 171 | Assert.AreEqual(rowData[i].Checksum, table.Rows[i, 4]); 172 | Assert.AreEqual(rowData[i].TimestampCreated, table.Rows[i, 5]); 173 | Assert.AreEqual(rowData[i].TimestampModified, table.Rows[i, 6]); 174 | } 175 | } 176 | 177 | [TestMethod] 178 | public void Mock_MockTable_FromType_with_AnonymousType_Test() 179 | { 180 | var table = MockTable.FromType(new[] 181 | { 182 | new 183 | { 184 | Id = 123, 185 | Name = "My Name" 186 | } 187 | }); 188 | 189 | Assert.AreEqual(123, table.Rows[0, 0]); 190 | Assert.AreEqual("My Name", table.Rows[0, 1]); 191 | } 192 | 193 | [TestMethod] 194 | public void Should_Only_Return_Properties_From_Whitelist() 195 | { 196 | using var context = new MyDbContext(); 197 | 198 | var entityTypeModel = context.Model.FindEntityTypes(typeof(NavigationModel)); 199 | var properties = entityTypeModel.FirstOrDefault().GetProperties().ToList(); 200 | var table = MockTable.FromType( 201 | null, 202 | System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.Instance, 203 | properties.Select(p => p.Name).ToArray() 204 | ); 205 | 206 | Assert.IsNotNull(table); 207 | 208 | Assert.AreEqual(7, table.Columns.Length); 209 | Assert.IsFalse(table.Columns.Any(c => c.Name == nameof(NavigationModel.RelatedModels))); 210 | } 211 | } 212 | 213 | public class MyDbContext : DbContext 214 | { 215 | public DbSet SimpleModels { get; set; } 216 | public DbSet RelatedModels { get; set; } 217 | 218 | protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) 219 | { 220 | optionsBuilder.UseSqlServer("YourConnectionStringHere"); 221 | } 222 | 223 | protected override void OnModelCreating(ModelBuilder modelBuilder) 224 | { 225 | modelBuilder.Entity() 226 | .HasMany(sm => sm.RelatedModels) 227 | .WithOne(rm => rm.NavigationModel) 228 | .HasForeignKey(rm => rm.NavigationModelId); 229 | 230 | base.OnModelCreating(modelBuilder); 231 | } 232 | } 233 | } 234 | -------------------------------------------------------------------------------- /DbMocker.Tests/DbMockTableTests.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Data.Common; 3 | using System.Diagnostics; 4 | using System.Linq; 5 | using Apps72.Dev.Data.DbMocker; 6 | using Apps72.Dev.Data.DbMocker.Helpers; 7 | using Microsoft.VisualStudio.TestTools.UnitTesting; 8 | 9 | namespace DbMocker.Tests 10 | { 11 | [TestClass] 12 | public class DbMockTableTests 13 | { 14 | [TestMethod] 15 | public void Mock_ReturnsScalar_MockTable_Test() 16 | { 17 | var conn = new MockDbConnection(); 18 | 19 | MockTable table = MockTable.Empty() 20 | .AddColumns("Col1") 21 | .AddRow(11); 22 | 23 | conn.Mocks 24 | .WhenAny() 25 | .ReturnsTable(table); 26 | 27 | DbCommand cmd = conn.CreateCommand(); 28 | object result = cmd.ExecuteScalar(); 29 | 30 | Assert.AreEqual(11, result); 31 | } 32 | 33 | [TestMethod] 34 | public void Mock_ReturnsScalar_MockTable_TypedColumns_Test() 35 | { 36 | var conn = new MockDbConnection(); 37 | 38 | MockTable table = MockTable.Empty() 39 | .AddColumns(("Col1", typeof(int))) 40 | .AddRow(11); 41 | 42 | conn.Mocks 43 | .WhenAny() 44 | .ReturnsTable(table); 45 | 46 | DbCommand cmd = conn.CreateCommand(); 47 | object result = cmd.ExecuteScalar(); 48 | 49 | Assert.AreEqual(11, result); 50 | } 51 | 52 | [TestMethod] 53 | public void Mock_ReturnsSimple_MockTable_Test() 54 | { 55 | var traced = false; 56 | var conn = new MockDbConnection(); 57 | 58 | MockTable table = MockTable.WithColumns("Col1", "Col2") 59 | .AddRow(11, 12) 60 | .AddRow(13, 14); 61 | conn.Mocks 62 | .WhenAny() 63 | .Callback(_ => { traced = true; }) 64 | .ReturnsTable(table); 65 | 66 | DbCommand cmd = conn.CreateCommand(); 67 | DbDataReader result = cmd.ExecuteReader(); 68 | 69 | result.Read(); 70 | 71 | Assert.IsTrue(traced); 72 | Assert.AreEqual(11, result.GetInt32(0)); 73 | Assert.AreEqual(12, result.GetInt32(1)); 74 | 75 | result.Read(); 76 | 77 | Assert.AreEqual(13, result.GetInt32(0)); 78 | Assert.AreEqual(14, result.GetInt32(1)); 79 | } 80 | 81 | [TestMethod] 82 | public void Mock_ReturnsSimple_MockRow_Test() 83 | { 84 | var conn = new MockDbConnection(); 85 | 86 | MockTable table = MockTable.WithColumns("Col1", "Col2") 87 | .AddRow(11, 12) 88 | .AddRow(13, 14); 89 | conn.Mocks 90 | .WhenAny() 91 | .ReturnsRow(table); 92 | 93 | DbCommand cmd = conn.CreateCommand(); 94 | DbDataReader result = cmd.ExecuteReader(); 95 | 96 | result.Read(); 97 | 98 | Assert.AreEqual(11, result.GetInt32(0)); 99 | Assert.AreEqual(12, result.GetInt32(1)); 100 | 101 | result.Read(); 102 | 103 | Assert.AreEqual(13, result.GetInt32(0)); 104 | Assert.AreEqual(14, result.GetInt32(1)); 105 | } 106 | 107 | [TestMethod] 108 | public void Mock_ReturnsSimple_MockTableWithNull_Test() 109 | { 110 | var conn = new MockDbConnection(); 111 | 112 | MockTable table = MockTable.WithColumns("Col1", "Col2") 113 | .AddRow(null, 12) 114 | .AddRow(13, 14); 115 | conn.Mocks 116 | .WhenAny() 117 | .ReturnsTable(table); 118 | 119 | DbCommand cmd = conn.CreateCommand(); 120 | DbDataReader result = cmd.ExecuteReader(); 121 | 122 | result.Read(); 123 | 124 | Assert.AreEqual(null, result.GetValue(0)); 125 | Assert.IsTrue(result.GetFieldType(0) == typeof(object)); 126 | 127 | result.Read(); 128 | 129 | Assert.AreEqual(13, result.GetValue(0)); 130 | Assert.IsTrue(result.GetFieldType(0) == typeof(object)); 131 | } 132 | 133 | [TestMethod] 134 | public void Mock_ReturnsSimple_MockTypedTable_Test() 135 | { 136 | var conn = new MockDbConnection(); 137 | 138 | MockTable table = MockTable.WithColumns(("Col1", typeof(int?)), 139 | ("Col2", typeof(int))) 140 | .AddRow(null, 12) 141 | .AddRow(13, 14); 142 | conn.Mocks 143 | .WhenAny() 144 | .ReturnsTable(table); 145 | 146 | DbCommand cmd = conn.CreateCommand(); 147 | DbDataReader result = cmd.ExecuteReader(); 148 | 149 | result.Read(); 150 | 151 | Assert.AreEqual(null, result.GetValue(0)); 152 | Assert.IsTrue(result.GetFieldType(0) == typeof(int?)); 153 | 154 | Assert.AreEqual(12, result.GetValue(1)); 155 | Assert.IsTrue(result.GetFieldType(1) == typeof(int)); 156 | } 157 | 158 | [TestMethod] 159 | public void Mock_ReturnsSimple_DBNull_Test() 160 | { 161 | var traced = false; 162 | var conn = new MockDbConnection(); 163 | 164 | conn.Mocks 165 | .WhenAny() 166 | .Callback(_ => { traced = true; }) 167 | .ReturnsScalar(DBNull.Value); 168 | 169 | object result = conn.CreateCommand().ExecuteScalar(); 170 | 171 | Assert.IsTrue(traced); 172 | Assert.AreEqual(DBNull.Value, result); 173 | } 174 | 175 | [TestMethod] 176 | public void Mock_ReturnsSimple_Null_Test() 177 | { 178 | var conn = new MockDbConnection(); 179 | 180 | conn.Mocks 181 | .WhenAny() 182 | .ReturnsScalar(DBNull.Value); 183 | 184 | object result = conn.CreateCommand().ExecuteScalar(); 185 | 186 | Assert.AreEqual(DBNull.Value, result); 187 | } 188 | 189 | [TestMethod] 190 | public void Mock_ReturnsRow_DBNull_Test() 191 | { 192 | var conn = new MockDbConnection(); 193 | 194 | conn.Mocks 195 | .WhenAny() 196 | .ReturnsRow(new { id = 1, Name = DBNull.Value }); 197 | 198 | DbDataReader result = conn.CreateCommand().ExecuteReader(); 199 | 200 | result.Read(); 201 | 202 | Assert.AreEqual(1, result.GetInt32(0)); 203 | Assert.AreEqual(true, result.IsDBNull(1)); 204 | } 205 | 206 | [TestMethod] 207 | public void Mock_ReturnsRow_Null_Test() 208 | { 209 | var conn = new MockDbConnection(); 210 | 211 | conn.Mocks 212 | .WhenAny() 213 | .ReturnsRow(new { id = 1, Name = (string)null }); 214 | 215 | DbDataReader result = conn.CreateCommand().ExecuteReader(); 216 | 217 | result.Read(); 218 | 219 | Assert.AreEqual(1, result.GetInt32(0)); 220 | Assert.AreEqual(true, result.IsDBNull(1)); 221 | } 222 | 223 | [TestMethod] 224 | public void Mock_ReturnsRow_ByteArray_Test() 225 | { 226 | var conn = new MockDbConnection(); 227 | conn.Mocks 228 | .WhenAny() 229 | .ReturnsRow(new { Hash = new byte[] { 0, 1, 2, 4, 0, 0 } }); 230 | 231 | var reader = conn.CreateCommand().ExecuteReader(); 232 | reader.Read(); 233 | var buffer = new byte[] { 0, 0, 0, 0, 0, 0 }; 234 | var readBytesCount = reader.GetBytes(0, 1, buffer, 2, 3); 235 | 236 | Assert.AreEqual(buffer[2], 1); 237 | Assert.AreEqual(buffer[3], 2); 238 | Assert.AreEqual(buffer[4], 4); 239 | } 240 | 241 | [TestMethod] 242 | public void Mock_ReturnsScalar_MockTableSingle_Test() 243 | { 244 | var conn = new MockDbConnection(); 245 | 246 | var table = MockTable.SingleCell("Col1", 11); 247 | 248 | conn.Mocks 249 | .WhenAny() 250 | .ReturnsTable(table); 251 | 252 | DbCommand cmd = conn.CreateCommand(); 253 | object result = cmd.ExecuteScalar(); 254 | 255 | Assert.AreEqual(11, result); 256 | } 257 | 258 | [TestMethod] 259 | public void Mock_ReturnsScalar_MockTableSingleWithoutColumnName_Test() 260 | { 261 | var conn = new MockDbConnection(); 262 | 263 | var table = MockTable.SingleCell(11); 264 | conn.Mocks 265 | .WhenAny() 266 | .ReturnsTable(table); 267 | 268 | DbCommand cmd = conn.CreateCommand(); 269 | object result = cmd.ExecuteScalar(); 270 | 271 | Assert.AreEqual(11, result); 272 | } 273 | 274 | [TestMethod] 275 | public void Mock_MockTable_FromCsv_Test() 276 | { 277 | var conn = new MockDbConnection(); 278 | 279 | string csv = @" Id Name Birthdate 280 | 1 Scott 1980-02-03 281 | 2 Bill 1972-01-12 282 | 3 Anders 1965-03-14 "; 283 | 284 | var table = MockTable.FromCsv(csv); 285 | 286 | Assert.AreEqual("Id", table.Columns[0].Name); 287 | Assert.AreEqual("Name", table.Columns[1].Name); 288 | 289 | Assert.AreEqual(3, table.Rows.RowsCount()); 290 | 291 | Assert.AreEqual("Scott", table.Rows[0, 1]); 292 | Assert.IsInstanceOfType(table.Rows[0, 1], typeof(string)); 293 | 294 | Assert.AreEqual(3, table.Rows[2, 0]); 295 | Assert.IsInstanceOfType(table.Rows[2, 0], typeof(int)); 296 | 297 | Assert.AreEqual(new DateTime(1972, 1, 12), table.Rows[1, 2]); 298 | Assert.IsInstanceOfType(table.Rows[1, 2], typeof(DateTime)); 299 | } 300 | 301 | [TestMethod] 302 | public void Mock_CheckException_Test() 303 | { 304 | var conn = new MockDbConnection(); 305 | 306 | conn.Mocks 307 | .WhenTag("NotFoundTag") 308 | .ReturnsScalar(99); 309 | 310 | DbCommand cmd = conn.CreateCommand(); 311 | cmd.CommandText = "SELECT * FROM EMP"; 312 | 313 | DbParameter myParam = cmd.CreateParameter(); 314 | myParam.ParameterName = "MyParam"; 315 | cmd.Parameters.Add(myParam); 316 | 317 | try 318 | { 319 | object result = cmd.ExecuteScalar(); 320 | } 321 | catch (MockException ex) 322 | { 323 | Assert.AreEqual("SELECT * FROM EMP", ex.CommandText); 324 | Assert.AreEqual("MyParam", ex.Parameters.First().ParameterName); 325 | } 326 | } 327 | } 328 | } 329 | -------------------------------------------------------------------------------- /DbMocker.Tests/DbMockTagsTests.cs: -------------------------------------------------------------------------------- 1 | using Apps72.Dev.Data; 2 | using Apps72.Dev.Data.DbMocker; 3 | using Microsoft.VisualStudio.TestTools.UnitTesting; 4 | using System; 5 | using System.Data.SqlClient; 6 | using System.Linq; 7 | using System.Text; 8 | 9 | namespace DbMocker.Tests 10 | { 11 | [TestClass] 12 | public class DbMockTagsTests 13 | { 14 | [TestMethod] 15 | public void Mock_SimpleTag_Test() 16 | { 17 | var conn = new MockDbConnection(); 18 | 19 | conn.Mocks 20 | .WhenTag("MyTag") 21 | .ReturnsScalar(99); 22 | 23 | var cmd = conn.CreateCommand(); 24 | cmd.CommandText = @"-- MyTag 25 | SELECT ... "; 26 | var result = cmd.ExecuteScalar(); 27 | 28 | Assert.AreEqual(99, result); 29 | } 30 | 31 | [TestMethod] 32 | public void Mock_MultipleTags_Test() 33 | { 34 | var conn = new MockDbConnection(); 35 | 36 | conn.Mocks 37 | .WhenTag("MyTag") 38 | .ReturnsScalar(99); 39 | 40 | var sql = new StringBuilder(); 41 | sql.AppendLine("-- Tag1"); 42 | sql.AppendLine("-- MyTag"); 43 | sql.AppendLine("-- Tag2"); 44 | sql.AppendLine("SELECT ... "); 45 | 46 | var cmd = conn.CreateCommand(); 47 | cmd.CommandText = sql.ToString(); 48 | var result = cmd.ExecuteScalar(); 49 | 50 | Assert.AreEqual(99, result); 51 | } 52 | 53 | [DataTestMethod()] 54 | [DataRow("\r")] 55 | [DataRow("\r\n")] 56 | [DataRow("\n\r")] 57 | [DataRow("\n")] 58 | public void Mock_SimpleTag_WithReturnSeparators_Test(string crlf) 59 | { 60 | var conn = new MockDbConnection(); 61 | 62 | conn.Mocks 63 | .WhenTag("MyTag") 64 | .ReturnsScalar(99); 65 | 66 | var cmd = conn.CreateCommand(); 67 | cmd.CommandText = $"-- MyTag{crlf}SELECT ... "; 68 | var result = cmd.ExecuteScalar(); 69 | 70 | Assert.AreEqual(99, result); 71 | } 72 | 73 | [TestMethod] 74 | [ExpectedException(typeof(MockException))] 75 | public void Mock_TagNotFound_Test() 76 | { 77 | var conn = new MockDbConnection(); 78 | 79 | conn.Mocks 80 | .WhenTag("MyTag") 81 | .ReturnsScalar(99); 82 | 83 | var cmd = conn.CreateCommand(); 84 | cmd.CommandText = "SELECT ... "; 85 | var result = cmd.ExecuteScalar(); 86 | } 87 | 88 | [TestMethod] 89 | [ExpectedException(typeof(MockException))] 90 | public void Mock_TagMustStartLine_Test() 91 | { 92 | var conn = new MockDbConnection(); 93 | 94 | conn.Mocks 95 | .WhenTag("MyTag") 96 | .ReturnsScalar(99); 97 | 98 | var cmd = conn.CreateCommand(); // First char is a space 99 | cmd.CommandText = @" -- MyTag 100 | SELECT ... "; 101 | var result = cmd.ExecuteScalar(); 102 | } 103 | 104 | [TestMethod] 105 | [ExpectedException(typeof(MockException))] 106 | public void Mock_TagMustBeAlone_Test() 107 | { 108 | var conn = new MockDbConnection(); 109 | 110 | conn.Mocks 111 | .WhenTag("MyTag") 112 | .ReturnsScalar(99); 113 | 114 | var cmd = conn.CreateCommand(); // There are other chars after MyTag 115 | cmd.CommandText = @"-- MyTag... 116 | SELECT ... "; 117 | var result = cmd.ExecuteScalar(); 118 | } 119 | } 120 | } 121 | -------------------------------------------------------------------------------- /DbMocker.Tests/DbMockTests.cs: -------------------------------------------------------------------------------- 1 | using Apps72.Dev.Data.DbMocker; 2 | using Apps72.Dev.Data.DbMocker.Data; 3 | using Apps72.Dev.Data.DbMocker.Helpers; 4 | using Microsoft.VisualStudio.TestTools.UnitTesting; 5 | using System; 6 | using System.Linq; 7 | 8 | namespace DbMocker.Tests 9 | { 10 | [TestClass] 11 | public class DbMockTests 12 | { 13 | [TestMethod] 14 | public void Mock_CheckTwoDimensionalObject_Test() 15 | { 16 | var x = new object[,] 17 | { 18 | { "Col1", "Col2" }, 19 | { "abc" , "def" }, 20 | { "ghi" , "jkl" } 21 | }; 22 | var y = new object[,] 23 | { 24 | { }, 25 | }; 26 | var z = new object[,] 27 | { 28 | }; 29 | 30 | Assert.AreEqual(2, x.Rank); 31 | Assert.AreEqual(6, x.Length); 32 | Assert.AreEqual(3, x.GetLength(0)); 33 | Assert.AreEqual(2, x.GetLength(1)); 34 | Assert.AreEqual("Col1", x[0, 0]); 35 | Assert.AreEqual("Col2", x[0, 1]); 36 | 37 | Assert.AreEqual(2, y.Rank); 38 | Assert.AreEqual(0, y.Length); 39 | Assert.AreEqual(1, y.GetLength(0)); 40 | Assert.AreEqual(0, y.GetLength(1)); 41 | 42 | Assert.AreEqual(2, z.Rank); 43 | Assert.AreEqual(0, z.Length); 44 | Assert.AreEqual(0, z.GetLength(0)); 45 | Assert.AreEqual(0, z.GetLength(1)); 46 | } 47 | 48 | [TestMethod] 49 | public void Mock_ConvertToJaggedArray_Test() 50 | { 51 | var source = new object[,] 52 | { 53 | { "Col1", "Col2" }, 54 | { "abc" , "def" }, 55 | { "ghi" , "jkl" } 56 | }; 57 | 58 | var target = source.ToJaggedArray(); 59 | 60 | Assert.AreEqual("Col1", target[0][0]); 61 | Assert.AreEqual("def", target[1][1]); 62 | Assert.AreEqual("ghi", target[2][0]); 63 | } 64 | 65 | [TestMethod] 66 | public void Mock_ConnectionProperties_Test() 67 | { 68 | var conn = new MockDbConnection(); 69 | 70 | Assert.AreEqual("Server=DbMockerServer;Database=DbMockerDatabase", conn.ConnectionString); 71 | Assert.AreEqual("DbMockerDatabase", conn.Database); 72 | Assert.AreEqual("DbMockerServer", conn.DataSource); 73 | Assert.AreEqual("1.0", conn.ServerVersion); 74 | } 75 | 76 | [TestMethod] 77 | public void Mock_BeginTransaction_Test() 78 | { 79 | var conn = new MockDbConnection(); 80 | conn.Mocks.WhenAny().ReturnsScalar(14); 81 | 82 | using (var trans = conn.BeginTransaction()) 83 | { 84 | var result = conn.CreateCommand().ExecuteScalar(); 85 | trans.Rollback(); 86 | 87 | Assert.AreEqual(14, result); 88 | } 89 | } 90 | 91 | [TestMethod] 92 | public void Mock_ConvertToTwoDimensionalArray_Test() 93 | { 94 | var source = new object[][] 95 | { 96 | new [] { "Col1", "Col2" }, 97 | new [] { "abc" , "def" }, 98 | new [] { "ghi" , "jkl" } 99 | }; 100 | 101 | var target = source.ToTwoDimensionalArray(); 102 | 103 | Assert.AreEqual("Col1", target[0, 0]); 104 | Assert.AreEqual("def", target[1, 1]); 105 | Assert.AreEqual("ghi", target[2, 0]); 106 | } 107 | 108 | [TestMethod] 109 | public void Mock_ReturnsMockTable_Properties_Test() 110 | { 111 | var conn = new MockDbConnection(); 112 | 113 | conn.Mocks 114 | .When(c => c.CommandText.Contains("SELECT")) 115 | .ReturnsTable(new MockTable() 116 | { 117 | Columns = Columns.WithNames("X"), 118 | Rows = new object[,] 119 | { 120 | { 14 } 121 | } 122 | }); 123 | 124 | var cmd = conn.CreateCommand(); 125 | cmd.CommandText = "SELECT COUNT(*) FROM EMP"; 126 | var result = cmd.ExecuteScalar(); 127 | 128 | Assert.AreEqual(14, result); 129 | } 130 | 131 | [TestMethod] 132 | public void Mock_ReturnsMockTable_Constructor_Test() 133 | { 134 | var conn = new MockDbConnection(); 135 | 136 | conn.Mocks 137 | .When(c => c.CommandText.Contains("SELECT")) 138 | .ReturnsTable(new MockTable(columns: new[] { "X" }, 139 | rows: new object[,] 140 | { 141 | { 14 } 142 | })); 143 | var cmd = conn.CreateCommand(); 144 | cmd.CommandText = "SELECT COUNT(*) FROM EMP"; 145 | var result = cmd.ExecuteScalar(); 146 | 147 | Assert.AreEqual(14, result); 148 | } 149 | 150 | [TestMethod] 151 | public void Mock_ReturnsEmptyTable_Test() 152 | { 153 | var conn = new MockDbConnection(); 154 | 155 | conn.Mocks 156 | .WhenAny() 157 | .ReturnsTable(new MockTable()); 158 | 159 | var cmd = conn.CreateCommand(); 160 | cmd.CommandText = "SELECT COUNT(*) FROM EMP"; 161 | var result = cmd.ExecuteScalar(); 162 | 163 | Assert.AreEqual(null, result); 164 | } 165 | 166 | [TestMethod] 167 | [ExpectedException(typeof(MockException))] 168 | public void Mock_MockNotFound_Test() 169 | { 170 | var conn = new MockDbConnection(); 171 | 172 | conn.Mocks 173 | .When(c => c.CommandText.Contains("NOT PRESENT")) 174 | .ReturnsScalar(14); 175 | 176 | var cmd = conn.CreateCommand(); 177 | cmd.CommandText = "SELECT COUNT(*) FROM EMP"; 178 | var result = cmd.ExecuteScalar(); 179 | } 180 | 181 | [TestMethod] 182 | public void Mock_ReturnsRow_ExpressionTo_TypedData_Test() 183 | { 184 | var conn = new MockDbConnection(); 185 | 186 | conn.Mocks 187 | .WhenAny() 188 | .ReturnsRow((c) => new { Id = 11, Name = "Denis" }); 189 | 190 | var cmd = conn.CreateCommand(); 191 | var result = cmd.ExecuteReader(); 192 | 193 | result.Read(); 194 | 195 | Assert.AreEqual(11, result.GetInt32(0)); 196 | Assert.AreEqual("Denis", result.GetString(1)); 197 | Assert.AreEqual(false, result.Read()); 198 | } 199 | 200 | [TestMethod] 201 | public void Mock_ReturnsRow_TypedData_Test() 202 | { 203 | var conn = new MockDbConnection(); 204 | 205 | conn.Mocks 206 | .WhenAny() 207 | .ReturnsRow(new { Id = 11, Name = "Denis" }); 208 | 209 | var cmd = conn.CreateCommand(); 210 | var result = cmd.ExecuteReader(); 211 | 212 | result.Read(); 213 | 214 | Assert.AreEqual(11, result.GetInt32(0)); 215 | Assert.AreEqual("Denis", result.GetString(1)); 216 | Assert.AreEqual(false, result.Read()); 217 | } 218 | 219 | [TestMethod] 220 | public void Mock_ReturnsRow_PrimitiveType_Test() 221 | { 222 | var conn = new MockDbConnection(); 223 | 224 | conn.Mocks 225 | .WhenAny() 226 | .ReturnsRow(11); 227 | 228 | var cmd = conn.CreateCommand(); 229 | var result = cmd.ExecuteReader(); 230 | 231 | result.Read(); 232 | 233 | Assert.AreEqual(11, result.GetInt32(0)); 234 | Assert.AreEqual(false, result.Read()); 235 | } 236 | 237 | [TestMethod] 238 | public void Mock_ReturnsScalarValue_Test() 239 | { 240 | var conn = new MockDbConnection(); 241 | 242 | conn.Mocks 243 | .When(c => c.CommandText.Contains("SELECT")) 244 | .ReturnsScalar(14); 245 | 246 | var cmd = conn.CreateCommand(); 247 | cmd.CommandText = "SELECT COUNT(*) FROM EMP"; 248 | var result = cmd.ExecuteScalar(); 249 | 250 | Assert.AreEqual(14, result); 251 | } 252 | 253 | [TestMethod] 254 | public void Mock_ReturnsScalarValueFromFunction_Test() 255 | { 256 | var conn = new MockDbConnection(); 257 | 258 | conn.Mocks 259 | .When(c => c.CommandText.Contains("SELECT")) 260 | .ReturnsScalar(c => 14); 261 | 262 | var cmd = conn.CreateCommand(); 263 | cmd.CommandText = "SELECT COUNT(*) FROM EMP"; 264 | var result = cmd.ExecuteScalar(); 265 | 266 | Assert.AreEqual(14, result); 267 | } 268 | 269 | [TestMethod] 270 | public void Mock_ReturnsScalarValueFromParameter_Test() 271 | { 272 | var conn = new MockDbConnection(); 273 | 274 | conn.Mocks 275 | .When(c => c.CommandText.Contains("SELECT")) 276 | .ReturnsScalar(c => 2 * (c.Parameters.First(p => p.ParameterName == "MyParam").Value as int?)); 277 | 278 | var cmd = conn.CreateCommand(); 279 | cmd.CommandText = "SELECT COUNT(*) FROM EMP"; 280 | cmd.Parameters.Add(new MockDbParameter() { ParameterName = "MyParam", Value = 7 }); 281 | var result = cmd.ExecuteScalar(); 282 | 283 | Assert.AreEqual(14, result); 284 | } 285 | 286 | 287 | [TestMethod] 288 | public void Mock_ReturnsScalarValueFromNullParameter_Test() 289 | { 290 | var conn = new MockDbConnection(); 291 | 292 | conn.Mocks 293 | .WhenAny() 294 | .ReturnsScalar(99); 295 | 296 | var cmd = conn.CreateCommand(); 297 | 298 | // Create a Null Parameter 299 | var param = cmd.CreateParameter(); 300 | param.ParameterName = "@Myparam"; 301 | param.Value = null; 302 | cmd.Parameters.Add(param); 303 | 304 | var result = cmd.ExecuteScalar(); 305 | 306 | Assert.AreEqual(99, result); 307 | } 308 | 309 | [TestMethod] 310 | public void Mock_ReturnsScalarValueFromDBNullParameter_Test() 311 | { 312 | var conn = new MockDbConnection(); 313 | 314 | conn.Mocks 315 | .WhenAny() 316 | .ReturnsScalar(99); 317 | 318 | var cmd = conn.CreateCommand(); 319 | 320 | // Create a DBNull Parameter 321 | var param = cmd.CreateParameter(); 322 | param.ParameterName = "@Myparam"; 323 | param.Value = DBNull.Value; 324 | cmd.Parameters.Add(param); 325 | 326 | var result = cmd.ExecuteScalar(); 327 | 328 | Assert.AreEqual(99, result); 329 | } 330 | 331 | [TestMethod] 332 | public void Mock_SecondMockFound_Test() 333 | { 334 | var conn = new MockDbConnection(); 335 | 336 | conn.Mocks 337 | .When(c => c.CommandText.Contains("NO")) 338 | .ReturnsScalar(99); 339 | 340 | conn.Mocks 341 | .When(c => c.CommandText.Contains("SELECT")) 342 | .ReturnsScalar(14); 343 | 344 | var cmd = conn.CreateCommand(); 345 | cmd.CommandText = "SELECT COUNT(*) FROM EMP"; 346 | var result = cmd.ExecuteScalar(); 347 | 348 | Assert.AreEqual(14, result); 349 | } 350 | 351 | [TestMethod] 352 | public void Mock_ReturnsTableFunction_Test() 353 | { 354 | var conn = new MockDbConnection(); 355 | 356 | conn.Mocks 357 | .When(c => c.CommandText.Contains("SELECT")) 358 | .ReturnsTable(c => new MockTable( 359 | columns: new[] { "X" }, 360 | rows: new object[,] 361 | { 362 | { 10 } 363 | })); 364 | 365 | var cmd = conn.CreateCommand(); 366 | cmd.CommandText = "SELECT ..."; // This string contains 10 chars 367 | var result = cmd.ExecuteScalar(); 368 | 369 | Assert.AreEqual(10, result); 370 | } 371 | 372 | [TestMethod] 373 | public void Mock_ReturnsScalarFunction_Test() 374 | { 375 | var conn = new MockDbConnection(); 376 | 377 | conn.Mocks 378 | .When(c => c.CommandText.Contains("SELECT")) 379 | .ReturnsScalar(c => c.CommandText.Length); 380 | 381 | var cmd = conn.CreateCommand(); 382 | cmd.CommandText = "SELECT ..."; // This string contains 10 chars 383 | var result = cmd.ExecuteScalar(); 384 | 385 | Assert.AreEqual(10, result); 386 | } 387 | 388 | [TestMethod] 389 | public void Mock_Dispose_Test() 390 | { 391 | var conn = new MockDbConnection(); 392 | 393 | conn.Dispose(); 394 | Assert.AreEqual(conn.State, System.Data.ConnectionState.Closed); 395 | } 396 | 397 | [TestMethod] 398 | public void Mock_UsingDispose_Test() 399 | { 400 | MockDbConnection conn; 401 | 402 | using (conn = new MockDbConnection()) 403 | { 404 | 405 | } 406 | 407 | Assert.AreEqual(conn.State, System.Data.ConnectionState.Closed); 408 | } 409 | 410 | [TestMethod] 411 | public void Mock_Close_Test() 412 | { 413 | var conn = new MockDbConnection(); 414 | 415 | conn.Close(); 416 | Assert.AreEqual(conn.State, System.Data.ConnectionState.Closed); 417 | } 418 | } 419 | } 420 | -------------------------------------------------------------------------------- /DbMocker.Tests/DbMocker.Tests.csproj: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | net8.0 5 | false 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | 32 | 33 | 34 | 35 | 36 | 37 | -------------------------------------------------------------------------------- /DbMocker.Tests/SampleTypes/NavgiationModel.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | 4 | namespace DbMocker.Tests.SampleTypes 5 | { 6 | public class NavigationModel : SimpleModel 7 | { 8 | public ICollection RelatedModels { get; set; } 9 | 10 | public static new NavigationModel RandomInstance() 11 | { 12 | var model = SimpleModel.RandomInstance() as NavigationModel; 13 | model.RelatedModels = new List() 14 | { 15 | new RelatedModel() { Id = 1, Name = "Related 1" }, 16 | new RelatedModel() { Id = 2, Name = "Related 2" }, 17 | new RelatedModel() { Id = 3, Name = "Related 3" }, 18 | }; 19 | 20 | return model; 21 | } 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /DbMocker.Tests/SampleTypes/RelatedModel.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | 3 | namespace DbMocker.Tests.SampleTypes 4 | { 5 | public class RelatedModel 6 | { 7 | public int Id { get; set; } 8 | public string Name { get; set; } 9 | 10 | // Foreign key 11 | public Guid NavigationModelId { get; set; } 12 | 13 | // Navigation property 14 | public NavigationModel NavigationModel { get; set; } 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /DbMocker.Tests/SampleTypes/SimpleModel.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | 3 | namespace DbMocker.Tests.SampleTypes 4 | { 5 | public class SimpleModel 6 | { 7 | public Guid Id { get; set; } 8 | public string Name { get; set; } 9 | public string Description { get; set; } 10 | public int Value { get; set; } 11 | public long? Checksum { get; set; } 12 | public DateTime TimestampCreated { get; set; } 13 | public DateTime? TimestampModified { get; set; } 14 | 15 | public static long RandomValue => DateTime.UtcNow.Ticks; 16 | 17 | public static SimpleModel RandomInstance() 18 | { 19 | return new SimpleModel() 20 | { 21 | Id = Guid.NewGuid(), 22 | Name = Guid.NewGuid().ToString(), 23 | Description = Guid.NewGuid().ToString(), 24 | Value = DateTime.UtcNow.Millisecond, 25 | TimestampCreated = DateTime.UtcNow 26 | }; 27 | } 28 | 29 | public SimpleModel CalculateChecksum() 30 | { 31 | Checksum = DateTime.UtcNow.Ticks; 32 | return SetUpdated(); 33 | } 34 | 35 | public SimpleModel SetUpdated() 36 | { 37 | TimestampModified = DateTime.UtcNow; 38 | return this; 39 | } 40 | } 41 | } 42 | -------------------------------------------------------------------------------- /DbMocker.Tests/Samples.cs: -------------------------------------------------------------------------------- 1 | using Apps72.Dev.Data.DbMocker; 2 | using Microsoft.VisualStudio.TestTools.UnitTesting; 3 | using System; 4 | using System.Linq; 5 | using System.Data.Common; 6 | using System.Collections.Generic; 7 | 8 | namespace DbMocker.Tests 9 | { 10 | [TestClass] 11 | public class Samples 12 | { 13 | [TestMethod] 14 | public void UnitTest0() 15 | { 16 | var conn = new MockDbConnection(); 17 | 18 | // The text file "123-EMPLOYEES.txt" is embedded in this project. 19 | // See the Samples folder. 20 | // - 123 is an identifier (as you want) 21 | // - EMPLOYEES is the CommandText Tag 22 | // See https://docs.microsoft.com/en-us/ef/core/querying/tags 23 | conn.Mocks.LoadTagsFromResources("123-EMPLOYEES"); 24 | 25 | // Call your "classic" methods to tests 26 | var data = GetEmployees(conn); 27 | 28 | // DbMocker read the embedded file 29 | // and associated the content to the tag 30 | Assert.AreEqual(2, data.Length); 31 | Assert.AreEqual("Scott", data[0][1]); 32 | Assert.AreEqual("Bill", data[1][1]); 33 | } 34 | 35 | // Sample method from your DataService 36 | public int GetNumberOfEmployees(DbConnection connection) 37 | { 38 | using (var cmd = connection.CreateCommand()) 39 | { 40 | cmd.CommandText = @"-- COUNT_EMPLOYEES 41 | SELECT COUNT(*) FROM Employees"; 42 | return Convert.ToInt32(cmd.ExecuteScalar()); 43 | } 44 | } 45 | 46 | // Sample method from your DataService 47 | public object[][] GetEmployees(DbConnection connection) 48 | { 49 | using (var cmd = connection.CreateCommand()) 50 | { 51 | cmd.CommandText = @"-- EMPLOYEES 52 | SELECT ID, Name FROM Employees"; 53 | var reader = cmd.ExecuteReader(); 54 | 55 | var data = new List(); 56 | while (reader.Read()) 57 | { 58 | var row = new object[reader.FieldCount]; 59 | reader.GetValues(row); 60 | data.Add(row); 61 | 62 | int id = reader.GetValue(0) == null ? 0 : reader.GetInt32(0); 63 | string name = reader.GetString(1); 64 | 65 | } 66 | 67 | return data.ToArray(); 68 | } 69 | } 70 | 71 | [TestMethod] 72 | public void UnitTest1() 73 | { 74 | var conn = new MockDbConnection(); 75 | 76 | // When a specific SQL command is detected, 77 | // Don't execute the query to your SQL Server, 78 | // But returns this MockTable. 79 | conn.Mocks 80 | .When(cmd => cmd.CommandText.Contains("COUNT_EMPLOYEES") && 81 | cmd.Parameters.Count() == 0) 82 | .ReturnsTable(MockTable.WithColumns("Count") 83 | .AddRow(14)); 84 | 85 | // Call your "classic" methods to tests 86 | int count = GetNumberOfEmployees(conn); 87 | 88 | Assert.AreEqual(14, count); 89 | } 90 | 91 | [TestMethod] 92 | public void UnitTest2() 93 | { 94 | var conn = new MockDbConnection(); 95 | 96 | conn.Mocks 97 | .WhenTag("EMPLOYEES") 98 | .ReturnsTable(new MockTable().AddColumns("ID", "Name") 99 | .AddRow(1, "Scott") 100 | .AddRow(2, "Bill")); 101 | 102 | var data = GetEmployees(conn); 103 | 104 | Assert.AreEqual("Scott", data[0][1]); 105 | } 106 | 107 | [TestMethod] 108 | public void UnitTest3() 109 | { 110 | var conn = new MockDbConnection(); 111 | 112 | conn.Mocks 113 | .WhenTag("EMPLOYEES") 114 | .ReturnsTable(MockTable.Empty() 115 | .AddColumns("ID", "Name") 116 | .AddRow(1, "Scott")); 117 | 118 | var data = GetEmployees(conn); 119 | 120 | Assert.AreEqual("Scott", data[0][1]); 121 | } 122 | 123 | [TestMethod] 124 | public void UnitTest4() 125 | { 126 | var conn = new MockDbConnection(); 127 | 128 | conn.Mocks 129 | .WhenTag("COUNT_EMPLOYEES") 130 | .ReturnsTable(MockTable.SingleCell("Count", 14)); 131 | 132 | int count = GetNumberOfEmployees(conn); 133 | 134 | Assert.AreEqual(14, count); 135 | } 136 | 137 | [TestMethod] 138 | public void UnitTest5() 139 | { 140 | var conn = new MockDbConnection(); 141 | 142 | conn.Mocks 143 | .WhenTag("COUNT_EMPLOYEES") 144 | .ReturnsTable(cmd => MockTable.SingleCell("Count", cmd.Parameters.Count())); 145 | 146 | int count = GetNumberOfEmployees(conn); 147 | 148 | Assert.AreEqual(0, count); 149 | } 150 | 151 | [TestMethod] 152 | public void UnitTest6() 153 | { 154 | var conn = new MockDbConnection(); 155 | 156 | conn.Mocks 157 | .WhenTag("COUNT_EMPLOYEES") 158 | .ReturnsScalar(14); 159 | 160 | int count = GetNumberOfEmployees(conn); 161 | 162 | Assert.AreEqual(14, count); 163 | } 164 | 165 | [TestMethod] 166 | public void UnitTest7() 167 | { 168 | var conn = new MockDbConnection(); 169 | 170 | conn.Mocks 171 | .WhenAny() 172 | .ReturnsTable(MockTable.WithColumns(("ID", typeof(int?)), 173 | ("Name", typeof(string))) 174 | .AddRow(null, "Scott") 175 | .AddRow(2, "Bill")); 176 | 177 | var data = GetEmployees(conn); 178 | 179 | Assert.AreEqual(null, data[0][0]); 180 | Assert.AreEqual("Scott", data[0][1]); 181 | } 182 | 183 | [TestMethod] 184 | public void UnitTest8() 185 | { 186 | var conn = new MockDbConnection(); 187 | 188 | // Sample data rows 189 | var samples = new[] 190 | { 191 | new { ID = 0, Name = "Scott" }, 192 | new { ID = 1, Name = "Denis" }, 193 | }; 194 | 195 | conn.Mocks 196 | .WhenTag("EMPLOYEES") 197 | .ReturnsTable(MockTable.FromType(samples)); 198 | 199 | var data = GetEmployees(conn); 200 | 201 | Assert.AreEqual(2, data.Length); 202 | Assert.AreEqual(0, data[0][0]); 203 | Assert.AreEqual("Scott", data[0][1]); 204 | } 205 | 206 | 207 | } 208 | } 209 | -------------------------------------------------------------------------------- /DbMocker.Tests/Samples/123-EMPLOYEES.txt: -------------------------------------------------------------------------------- 1 | Id Name Age 2 | (int) (string) (int?) 3 | 4 | 10 Scott 21 5 | 20 Bill NULL 6 | -------------------------------------------------------------------------------- /DbMocker.Tests/Samples/SampleTable1.txt: -------------------------------------------------------------------------------- 1 | Id Name Age Male 2 | (int) (string) (int?) (bool) 3 | 4 | 1 Denis 21 true 5 | 2 Anne NULL false 6 | -------------------------------------------------------------------------------- /DbMocker.Tests/Samples/SampleTable2.txt: -------------------------------------------------------------------------------- 1 | Id Birth 2 | (int) (datetime) 3 | 4 | 123 2020-01-12 5 | 456 2019-07-15 6 | -------------------------------------------------------------------------------- /DbMocker.Tests/Samples/XX-SampleTable1.txt: -------------------------------------------------------------------------------- 1 | Id Name Age 2 | (int) (string) (int?) 3 | 4 | 10 Denis 21 5 | 20 Anne NULL 6 | -------------------------------------------------------------------------------- /DbMocker.Tests/Samples_EFTests.cs: -------------------------------------------------------------------------------- 1 | using Apps72.Dev.Data.DbMocker; 2 | using Microsoft.EntityFrameworkCore; 3 | using Microsoft.VisualStudio.TestTools.UnitTesting; 4 | using System; 5 | using System.Data.Common; 6 | using System.Linq; 7 | 8 | namespace DbMocker.Tests 9 | { 10 | [TestClass] 11 | public class Samples_EFTests 12 | { 13 | // Sample method from your DataService 14 | public int GetNumberOfEmployees(CompanyContext context) 15 | { 16 | return context.Employees 17 | .TagWith("EMPLOYEES_COUNT") // This feature is new in EF Core 2.2. 18 | .Count(); 19 | } 20 | 21 | // Sample method from your DataService 22 | public Employee[] GetEmployees(CompanyContext context) 23 | { 24 | return context.Employees 25 | .TagWith("ALL_EMPLOYEES") // This feature is new in EF Core 2.2. 26 | .ToArray(); 27 | } 28 | 29 | [TestMethod] 30 | public void EF_NumberOfEmployees_Test() 31 | { 32 | var conn = new MockDbConnection(); 33 | 34 | conn.Mocks 35 | .WhenTag("EMPLOYEES_COUNT") 36 | .ReturnsScalar(14); 37 | 38 | using (var context = new CompanyContext(conn)) 39 | { 40 | int count = GetNumberOfEmployees(context); 41 | 42 | Assert.AreEqual(14, count); 43 | } 44 | } 45 | 46 | [TestMethod] 47 | public void EF_AllEmployees_Test() 48 | { 49 | var conn = new MockDbConnection(); 50 | 51 | conn.Mocks 52 | .WhenTag("ALL_EMPLOYEES") 53 | .ReturnsTable(new MockTable().AddColumns("Id", "Code", "Name") 54 | .AddRow(1, "802f2ae2-fd99-4f67-b01a-ccc5a72b4f72", "Scott") 55 | .AddRow(2, "649d095b-0dda-4cb6-a8c9-aafc56bab78f", "Bill")); 56 | 57 | using (var context = new CompanyContext(conn)) 58 | { 59 | var employees = GetEmployees(context); 60 | 61 | Assert.AreEqual(1, employees[0].Id); 62 | Assert.AreEqual("Scott", employees[0].Name); 63 | Assert.AreEqual(2, employees[1].Id); 64 | Assert.AreEqual("Bill", employees[1].Name); 65 | } 66 | } 67 | } 68 | 69 | #region Entity Framework Context 70 | 71 | public class CompanyContext : DbContext 72 | { 73 | private readonly DbConnection _dbConnection; 74 | 75 | public CompanyContext(DbConnection connection) 76 | { 77 | _dbConnection = connection; 78 | } 79 | 80 | public DbSet Employees { get; set; } 81 | 82 | protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) 83 | { 84 | optionsBuilder.UseSqlServer(_dbConnection); 85 | } 86 | } 87 | 88 | public class Employee 89 | { 90 | public int Id { get; set; } 91 | public Guid Code { get; set; } 92 | public string Name { get; set; } 93 | } 94 | 95 | #endregion 96 | } 97 | -------------------------------------------------------------------------------- /DbMocker.sln: -------------------------------------------------------------------------------- 1 |  2 | Microsoft Visual Studio Solution File, Format Version 12.00 3 | # Visual Studio Version 17 4 | VisualStudioVersion = 17.12.35309.182 5 | MinimumVisualStudioVersion = 10.0.40219.1 6 | Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "DbMocker", "DbMocker\DbMocker.csproj", "{2B1EE9B3-93D8-4209-907E-0D29DAC089D3}" 7 | EndProject 8 | Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "DbMocker.Tests", "DbMocker.Tests\DbMocker.Tests.csproj", "{2E00ABB2-ECB5-486E-B33E-2CE7531D1772}" 9 | EndProject 10 | Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Solution Items", "Solution Items", "{7F2EDDB2-DD57-42B4-8687-E1D0ED15D4E1}" 11 | ProjectSection(SolutionItems) = preProject 12 | .editorconfig = .editorconfig 13 | ReadMe.md = ReadMe.md 14 | EndProjectSection 15 | EndProject 16 | Global 17 | GlobalSection(SolutionConfigurationPlatforms) = preSolution 18 | Debug|Any CPU = Debug|Any CPU 19 | Release|Any CPU = Release|Any CPU 20 | EndGlobalSection 21 | GlobalSection(ProjectConfigurationPlatforms) = postSolution 22 | {2B1EE9B3-93D8-4209-907E-0D29DAC089D3}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 23 | {2B1EE9B3-93D8-4209-907E-0D29DAC089D3}.Debug|Any CPU.Build.0 = Debug|Any CPU 24 | {2B1EE9B3-93D8-4209-907E-0D29DAC089D3}.Release|Any CPU.ActiveCfg = Release|Any CPU 25 | {2B1EE9B3-93D8-4209-907E-0D29DAC089D3}.Release|Any CPU.Build.0 = Release|Any CPU 26 | {2E00ABB2-ECB5-486E-B33E-2CE7531D1772}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 27 | {2E00ABB2-ECB5-486E-B33E-2CE7531D1772}.Debug|Any CPU.Build.0 = Debug|Any CPU 28 | {2E00ABB2-ECB5-486E-B33E-2CE7531D1772}.Release|Any CPU.ActiveCfg = Release|Any CPU 29 | {2E00ABB2-ECB5-486E-B33E-2CE7531D1772}.Release|Any CPU.Build.0 = Release|Any CPU 30 | EndGlobalSection 31 | GlobalSection(SolutionProperties) = preSolution 32 | HideSolutionNode = FALSE 33 | EndGlobalSection 34 | GlobalSection(ExtensibilityGlobals) = postSolution 35 | SolutionGuid = {43013FEE-E372-4866-91B7-2EFE840E3345} 36 | EndGlobalSection 37 | EndGlobal 38 | -------------------------------------------------------------------------------- /DbMocker/Data/MockDbCommand.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Data; 3 | using System.Data.Common; 4 | using System.Linq; 5 | 6 | namespace Apps72.Dev.Data.DbMocker.Data 7 | { 8 | /// 9 | public class MockDbCommand : DbCommand 10 | { 11 | private MockDbConnection _connection; 12 | 13 | /// 14 | internal MockDbCommand(MockDbConnection connection) 15 | { 16 | _connection = connection; 17 | this.DbConnection = _connection; 18 | this.Transaction = _connection.Transaction; 19 | this.DbParameterCollection = new MockDbParameterCollection(); 20 | } 21 | 22 | /// 23 | public override int ExecuteNonQuery() 24 | { 25 | int? returns = this.ExecuteScalar() as int?; 26 | 27 | if (returns.HasValue) 28 | return returns.Value; 29 | else 30 | return 0; 31 | } 32 | 33 | /// 34 | public override object ExecuteScalar() 35 | { 36 | return _connection.Mocks 37 | .GetFirstMockTablesFound(new MockCommand(this)) 38 | .First() 39 | .GetFirstColRowOrNull(); 40 | } 41 | 42 | /// 43 | protected override DbDataReader ExecuteDbDataReader(CommandBehavior behavior) 44 | { 45 | var result = _connection.Mocks 46 | .GetFirstMockTablesFound(new MockCommand(this)); 47 | 48 | return new MockDbDataReader(result); 49 | } 50 | 51 | #region LEGACY METHODS 52 | 53 | /// 54 | public override string CommandText { get; set; } 55 | 56 | /// 57 | public override int CommandTimeout { get; set; } = 60; 58 | 59 | /// 60 | public override CommandType CommandType { get; set; } = CommandType.Text; 61 | 62 | /// 63 | public override bool DesignTimeVisible { get; set; } = false; 64 | 65 | /// 66 | public override UpdateRowSource UpdatedRowSource { get; set; } = UpdateRowSource.None; 67 | 68 | /// 69 | protected override DbConnection DbConnection { get; set; } 70 | 71 | /// 72 | protected override DbParameterCollection DbParameterCollection { get; } 73 | 74 | /// 75 | protected override DbTransaction DbTransaction { get; set; } 76 | 77 | /// 78 | public override void Cancel() 79 | { 80 | } 81 | 82 | /// 83 | public override void Prepare() 84 | { 85 | } 86 | 87 | protected override DbParameter CreateDbParameter() 88 | { 89 | return new MockDbParameter(this); 90 | } 91 | 92 | #endregion 93 | } 94 | } 95 | -------------------------------------------------------------------------------- /DbMocker/Data/MockDbDataReader.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections; 3 | using System.Data; 4 | using System.Data.Common; 5 | 6 | namespace Apps72.Dev.Data.DbMocker.Data 7 | { 8 | public class MockDbDataReader : DbDataReader 9 | { 10 | private MockTable[] tables; 11 | private int _currentTableIndex = -1; 12 | private MockColumn[] _columns; 13 | private object[,] _rows; 14 | private int _currentRowIndex = -1; 15 | private DataTable _schema; 16 | private bool _isClosed = false; 17 | 18 | internal MockDbDataReader(MockTable[] tables) 19 | { 20 | this.tables = tables; 21 | NextResult(); 22 | } 23 | 24 | #region LEGACY METHODS 25 | 26 | public override object this[int ordinal] => GetValue(ordinal); 27 | 28 | public override object this[string name] => GetValue(GetOrdinal(name)); 29 | 30 | public override int Depth => 0; 31 | 32 | public override int FieldCount => _columns?.Length ?? 0; 33 | 34 | public override bool HasRows => _rows?.Length >= 1; 35 | 36 | public override bool IsClosed => _isClosed; 37 | 38 | public override int RecordsAffected => 0; 39 | 40 | public override bool GetBoolean(int ordinal) 41 | { 42 | return (bool)GetValue(ordinal); 43 | } 44 | 45 | public override byte GetByte(int ordinal) 46 | { 47 | return (byte)GetValue(ordinal); 48 | } 49 | 50 | public override long GetBytes(int ordinal, long dataOffset, byte[] buffer, int bufferOffset, int length) 51 | { 52 | var byteArray = (byte[])GetValue(ordinal); 53 | Array.Copy(byteArray, dataOffset, buffer, bufferOffset, length); 54 | return length; 55 | } 56 | 57 | public override char GetChar(int ordinal) 58 | { 59 | return (char)GetValue(ordinal); 60 | } 61 | 62 | public override long GetChars(int ordinal, long dataOffset, char[] buffer, int bufferOffset, int length) 63 | { 64 | return (long)GetValue(ordinal); 65 | } 66 | 67 | public override string GetDataTypeName(int ordinal) 68 | { 69 | return _columns[ordinal].Type.Name; 70 | } 71 | 72 | public override DateTime GetDateTime(int ordinal) 73 | { 74 | return (DateTime)GetValue(ordinal); 75 | } 76 | 77 | public override decimal GetDecimal(int ordinal) 78 | { 79 | return (Decimal)GetValue(ordinal); 80 | } 81 | 82 | public override double GetDouble(int ordinal) 83 | { 84 | return (double)GetValue(ordinal); 85 | } 86 | 87 | public override IEnumerator GetEnumerator() 88 | { 89 | throw new NotImplementedException(); 90 | } 91 | 92 | public override Type GetFieldType(int ordinal) 93 | { 94 | if (ordinal < _columns.Length) 95 | return _columns[ordinal].Type; 96 | else 97 | return GetValue(ordinal).GetType(); 98 | } 99 | 100 | public override float GetFloat(int ordinal) 101 | { 102 | return (float)GetValue(ordinal); 103 | } 104 | 105 | public override Guid GetGuid(int ordinal) 106 | { 107 | object value = GetValue(ordinal); 108 | if (value.GetType() == typeof(string)) 109 | { 110 | return new Guid(Convert.ToString(value)); 111 | } 112 | else 113 | { 114 | return (Guid)value; 115 | } 116 | } 117 | 118 | public override short GetInt16(int ordinal) 119 | { 120 | return (short)GetValue(ordinal); 121 | } 122 | 123 | public override int GetInt32(int ordinal) 124 | { 125 | return (int)GetValue(ordinal); 126 | } 127 | 128 | public override long GetInt64(int ordinal) 129 | { 130 | return (long)GetValue(ordinal); 131 | } 132 | 133 | public override string GetName(int ordinal) 134 | { 135 | return _columns[ordinal].Name; 136 | } 137 | 138 | public override int GetOrdinal(string name) 139 | { 140 | for (int i = 0; i < _columns.Length; i++) 141 | { 142 | if (String.Compare(_columns[i].Name, name, ignoreCase: true) == 0) 143 | return i; 144 | } 145 | return -1; 146 | } 147 | 148 | public override string GetString(int ordinal) 149 | { 150 | return (string)GetValue(ordinal); 151 | } 152 | 153 | public override object GetValue(int ordinal) 154 | { 155 | return _rows?[_currentRowIndex, ordinal]; 156 | } 157 | 158 | public override int GetValues(object[] values) 159 | { 160 | if (values != null) 161 | { 162 | for (int i = 0; i < values.Length; i++) 163 | { 164 | values[i] = _rows?[_currentRowIndex, i]; 165 | } 166 | return values.Length; 167 | } 168 | 169 | return 0; 170 | } 171 | 172 | public override bool IsDBNull(int ordinal) 173 | { 174 | return GetValue(ordinal) == DBNull.Value || 175 | GetValue(ordinal) == null; 176 | } 177 | 178 | public override bool NextResult() 179 | { 180 | _currentTableIndex++; 181 | 182 | if (_currentTableIndex >= tables.Length) 183 | { 184 | _isClosed = true; 185 | return false; 186 | } 187 | 188 | _columns = tables[_currentTableIndex].Columns ?? Array.Empty(); 189 | _rows = tables[_currentTableIndex].Rows ?? new object[,] { }; 190 | _currentRowIndex = -1; 191 | _schema = Helpers.MockDataReaderSchemaTableBuilder.BuildSchema(_columns, _rows); 192 | 193 | return true; 194 | } 195 | 196 | public override bool Read() 197 | { 198 | _currentRowIndex++; 199 | return _rows?.GetLength(0) > _currentRowIndex; 200 | } 201 | 202 | public override DataTable GetSchemaTable() 203 | { 204 | return _schema; 205 | } 206 | 207 | #endregion 208 | } 209 | } 210 | -------------------------------------------------------------------------------- /DbMocker/Data/MockDbParameter.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Data; 3 | using System.Data.Common; 4 | 5 | namespace Apps72.Dev.Data.DbMocker.Data 6 | { 7 | /// 8 | public class MockDbParameter : DbParameter 9 | { 10 | private bool _hasDbTypeIsDefined = false; // True when the DbType property is already setted and defined. 11 | private object _value = null; 12 | private DbType _dbType = DbType.AnsiString; 13 | private DbParameter _parameter; 14 | /// 15 | public MockDbParameter() 16 | { 17 | } 18 | 19 | /// 20 | internal MockDbParameter(DbParameter parameter) 21 | { 22 | if (parameter != null) 23 | { 24 | _parameter = parameter; 25 | this.DbType = parameter.DbType; 26 | this.Direction = parameter.Direction; 27 | this.IsNullable = parameter.IsNullable; 28 | this.ParameterName = parameter.ParameterName; 29 | this.Size = parameter.Size; 30 | this.SourceColumn = parameter.SourceColumn; 31 | this.SourceColumnNullMapping = parameter.SourceColumnNullMapping; 32 | this.SourceVersion = parameter.SourceVersion; 33 | this.Value = parameter.Value; 34 | } 35 | } 36 | 37 | #region LEGACY METHODS 38 | 39 | /// 40 | internal MockDbParameter(DbCommand command) { } 41 | /// 42 | public override DbType DbType 43 | { 44 | get 45 | { 46 | return _dbType; 47 | } 48 | set 49 | { 50 | _dbType = value; 51 | _hasDbTypeIsDefined = true; 52 | } 53 | } 54 | 55 | /// 56 | public override ParameterDirection Direction { get; set; } 57 | /// 58 | public override bool IsNullable { get; set; } 59 | /// 60 | public override string ParameterName { get; set; } 61 | /// 62 | public override int Size { get; set; } 63 | /// 64 | public override string SourceColumn { get; set; } 65 | /// 66 | public override bool SourceColumnNullMapping { get; set; } 67 | /// 68 | public override DataRowVersion SourceVersion { get; set; } 69 | /// 70 | public override object Value 71 | { 72 | get 73 | { 74 | return _value; 75 | } 76 | set 77 | { 78 | // set value to original dbParameter 79 | if (_parameter != null) 80 | _parameter.Value = value; 81 | 82 | _value = value; 83 | if (_hasDbTypeIsDefined == false) 84 | this.DbType = Helpers.DbTypeMap.FirstDbType(value?.GetType()); 85 | } 86 | } 87 | /// 88 | public override void ResetDbType() 89 | { 90 | } 91 | 92 | #endregion 93 | } 94 | } 95 | -------------------------------------------------------------------------------- /DbMocker/Data/MockDbParameterCollection.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections; 3 | using System.Collections.Generic; 4 | using System.Data.Common; 5 | using System.Linq; 6 | 7 | namespace Apps72.Dev.Data.DbMocker.Data 8 | { 9 | /// 10 | public class MockDbParameterCollection : DbParameterCollection 11 | { 12 | #region LEGACY METHODS 13 | 14 | private List _parameters = new List(); 15 | 16 | /// 17 | public override int Count => _parameters.Count(); 18 | 19 | /// 20 | public override object SyncRoot => null; 21 | 22 | /// 23 | public override bool IsSynchronized => true; 24 | 25 | /// 26 | public override bool IsReadOnly => false; 27 | 28 | /// 29 | public override bool IsFixedSize => false; 30 | 31 | /// 32 | public override int Add(object value) 33 | { 34 | _parameters.Add(new MockDbParameter(value as DbParameter)); 35 | return _parameters.Count(); 36 | } 37 | 38 | /// 39 | public override void AddRange(Array values) 40 | { 41 | _parameters.AddRange(values.Cast().Select(p => new MockDbParameter(p))); 42 | } 43 | 44 | /// 45 | public override void Clear() 46 | { 47 | _parameters.Clear(); 48 | } 49 | 50 | /// 51 | public override bool Contains(object value) 52 | { 53 | var dbParam = value as DbParameter; 54 | 55 | if (dbParam != null) 56 | return this.Contains(dbParam.ParameterName); 57 | else 58 | return false; 59 | } 60 | 61 | /// 62 | public override bool Contains(string value) 63 | { 64 | return _parameters.Any(p => String.Compare(p.ParameterName, value, ignoreCase: true) == 0); 65 | } 66 | 67 | /// 68 | public override void CopyTo(Array array, int index) 69 | { 70 | 71 | } 72 | 73 | /// 74 | public override IEnumerator GetEnumerator() 75 | { 76 | return _parameters.GetEnumerator(); 77 | } 78 | 79 | /// 80 | public override int IndexOf(object value) 81 | { 82 | return 0; 83 | } 84 | 85 | /// 86 | public override int IndexOf(string parameterName) 87 | { 88 | return 0; 89 | } 90 | 91 | /// 92 | public override void Insert(int index, object value) 93 | { 94 | _parameters.Add(new MockDbParameter(value as DbParameter)); 95 | } 96 | 97 | /// 98 | public override void Remove(object value) 99 | { 100 | 101 | } 102 | 103 | /// 104 | public override void RemoveAt(int index) 105 | { 106 | 107 | } 108 | 109 | /// 110 | public override void RemoveAt(string parameterName) 111 | { 112 | 113 | } 114 | 115 | /// 116 | protected override DbParameter GetParameter(int index) 117 | { 118 | return _parameters.Skip(index)?.FirstOrDefault(); 119 | } 120 | 121 | /// 122 | protected override DbParameter GetParameter(string parameterName) 123 | { 124 | return _parameters.FirstOrDefault(p => String.Compare(p.ParameterName, parameterName, ignoreCase: true) == 0); 125 | } 126 | 127 | /// 128 | protected override void SetParameter(int index, DbParameter value) 129 | { 130 | var dbParam = this.GetParameter(index); 131 | if (dbParam != null) 132 | dbParam = value; 133 | } 134 | 135 | /// 136 | protected override void SetParameter(string parameterName, DbParameter value) 137 | { 138 | var dbParam = this.GetParameter(parameterName); 139 | if (dbParam != null) 140 | dbParam = value; 141 | } 142 | 143 | #endregion 144 | } 145 | } 146 | -------------------------------------------------------------------------------- /DbMocker/Data/MockDbTransaction.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Data; 3 | using System.Data.Common; 4 | 5 | namespace Apps72.Dev.Data.DbMocker.Data 6 | { 7 | /// 8 | public class MockDbTransaction : DbTransaction 9 | { 10 | #region LEGACY METHODS 11 | 12 | private DbConnection _connection; 13 | 14 | /// 15 | internal MockDbTransaction(DbConnection connection) 16 | { 17 | _connection = connection; 18 | } 19 | 20 | /// 21 | public override IsolationLevel IsolationLevel => IsolationLevel.Unspecified; 22 | 23 | /// 24 | protected override DbConnection DbConnection => _connection; 25 | 26 | /// 27 | public override void Commit() 28 | { 29 | 30 | } 31 | 32 | /// 33 | public override void Rollback() 34 | { 35 | 36 | } 37 | 38 | #endregion 39 | } 40 | } 41 | -------------------------------------------------------------------------------- /DbMocker/DbMocker.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | netstandard2.0 5 | Apps72.Dev.Data.DbMocker 6 | Apps72.Dev.Data.DbMocker 7 | 1.26.0 8 | DbMocker 9 | MIT 10 | Denis Voituron 11 | DBMocker to validate and mock SQL Queries 12 | DbMocker 13 | This .NET library simplifies data mocking for UnitTests, to avoid a connection to a relational database. 14 | DbMocker use the standard Microsoft .NET DbConnection object. So, you can mock any toolkit, 15 | including EntityFramework, Dapper or ADO.NET; And for all database servers (SQL Server, Oracle, SQLite). 16 | 17 | ``` 18 | var conn = new MockDbConnection(); 19 | conn.Mocks 20 | .When(cmd => cmd.CommandText.Contains("SELECT COUNT(*) FROM EMP")) 21 | .ReturnsScalar(14); 22 | ``` 23 | 24 | Denis Voituron 25 | DbMocker, Mocker, SQLServer, Oracle, Sqlite, EntityFramework, EF, Dapper, UnitTest 26 | https://github.com/Apps72/DbMocker 27 | true 28 | 1.26.0.0 29 | https://github.com/Apps72/DbMocker 30 | https://github.com/Apps72/DbMocker 31 | 1.26.0.0 32 | 33 | 34 | 35 | 36 | 37 | 38 | 39 | -------------------------------------------------------------------------------- /DbMocker/Helpers/ArrayExtensions.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | 3 | namespace Apps72.Dev.Data.DbMocker.Helpers 4 | { 5 | public static class ArrayExtensions 6 | { 7 | /// 8 | public static T[][] ToJaggedArray(this T[,] twoDimensionalArray) 9 | { 10 | if (twoDimensionalArray == null) 11 | return null; 12 | 13 | int rowsFirstIndex = twoDimensionalArray.GetLowerBound(0); 14 | int rowsLastIndex = twoDimensionalArray.GetUpperBound(0); 15 | int numberOfRows = rowsLastIndex + 1; 16 | 17 | int columnsFirstIndex = twoDimensionalArray.GetLowerBound(1); 18 | int columnsLastIndex = twoDimensionalArray.GetUpperBound(1); 19 | int numberOfColumns = columnsLastIndex + 1; 20 | 21 | T[][] jaggedArray = new T[numberOfRows][]; 22 | for (int i = rowsFirstIndex; i <= rowsLastIndex; i++) 23 | { 24 | jaggedArray[i] = new T[numberOfColumns]; 25 | 26 | for (int j = columnsFirstIndex; j <= columnsLastIndex; j++) 27 | { 28 | jaggedArray[i][j] = twoDimensionalArray[i, j]; 29 | } 30 | } 31 | return jaggedArray; 32 | } 33 | 34 | /// 35 | public static T[,] ToTwoDimensionalArray(this T[][] jaggedArray) 36 | { 37 | if (jaggedArray == null) 38 | return null; 39 | 40 | int firstDimension = jaggedArray.Length; 41 | int secondDimension = 0; 42 | 43 | foreach (var row in jaggedArray) 44 | { 45 | if (row.Length > secondDimension) 46 | secondDimension = row.Length; 47 | } 48 | 49 | T[,] twoDimensionalArray = new T[firstDimension, secondDimension]; 50 | 51 | for (int i = 0; i < firstDimension; i++) 52 | { 53 | for (int j = 0; j < secondDimension; j++) 54 | { 55 | twoDimensionalArray[i, j] = jaggedArray[i][j]; 56 | } 57 | } 58 | 59 | return twoDimensionalArray; 60 | 61 | } 62 | 63 | /// 64 | public static int ColumnsCount(this object[,] twoDimensionalArray) 65 | { 66 | return twoDimensionalArray.GetLength(1); 67 | } 68 | 69 | /// 70 | public static int RowsCount(this object[,] twoDimensionalArray) 71 | { 72 | return twoDimensionalArray.GetLength(0); 73 | } 74 | } 75 | } 76 | -------------------------------------------------------------------------------- /DbMocker/Helpers/DbTypeMap.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Data; 4 | using System.Data.Common; 5 | using System.Linq; 6 | 7 | namespace Apps72.Dev.Data.DbMocker.Helpers 8 | { 9 | /// 10 | /// DbType Mapping. 11 | /// see https://github.com/Apps72/Dev.Data 12 | /// 13 | internal static class DbTypeMap 14 | { 15 | private static readonly List _dbTypeList = FillDbTypeList(); 16 | 17 | /// 18 | /// Returns the first DbType for this CLR Type. 19 | /// 20 | /// 21 | /// 22 | public static DbType FirstDbType(Type type) 23 | { 24 | if (type == null) return DbType.Object; 25 | var dbType = _dbTypeList.FirstOrDefault(i => i.Type == type); 26 | return dbType != null ? dbType.DbType : DbType.Object; 27 | } 28 | 29 | static List FillDbTypeList() 30 | { 31 | var list = new List(); 32 | 33 | list.Add(new Type2DbType(typeof(Int16), DbType.Int16)); 34 | list.Add(new Type2DbType(typeof(Int32), DbType.Int32)); 35 | list.Add(new Type2DbType(typeof(Int64), DbType.Int64)); 36 | list.Add(new Type2DbType(typeof(UInt16), DbType.UInt16)); 37 | list.Add(new Type2DbType(typeof(UInt32), DbType.UInt32)); 38 | list.Add(new Type2DbType(typeof(UInt64), DbType.UInt64)); 39 | list.Add(new Type2DbType(typeof(Boolean), DbType.Boolean)); 40 | list.Add(new Type2DbType(typeof(Byte), DbType.Byte)); 41 | list.Add(new Type2DbType(typeof(SByte), DbType.SByte)); 42 | list.Add(new Type2DbType(typeof(Decimal), DbType.Decimal)); 43 | list.Add(new Type2DbType(typeof(Decimal), DbType.Single)); 44 | list.Add(new Type2DbType(typeof(Double), DbType.Double)); 45 | list.Add(new Type2DbType(typeof(Decimal), DbType.Currency)); 46 | list.Add(new Type2DbType(typeof(Double), DbType.VarNumeric)); 47 | list.Add(new Type2DbType(typeof(Single), DbType.Single)); 48 | 49 | list.Add(new Type2DbType(typeof(Char), DbType.String)); 50 | list.Add(new Type2DbType(typeof(String), DbType.String)); 51 | list.Add(new Type2DbType(typeof(String), DbType.AnsiString)); 52 | list.Add(new Type2DbType(typeof(String), DbType.AnsiStringFixedLength)); 53 | list.Add(new Type2DbType(typeof(String), DbType.Xml)); 54 | 55 | list.Add(new Type2DbType(typeof(DateTime), DbType.DateTime)); 56 | list.Add(new Type2DbType(typeof(DateTime), DbType.Date)); 57 | list.Add(new Type2DbType(typeof(DateTime), DbType.DateTime2)); 58 | list.Add(new Type2DbType(typeof(DateTime), DbType.DateTime)); 59 | list.Add(new Type2DbType(typeof(DateTimeOffset), DbType.DateTimeOffset)); 60 | list.Add(new Type2DbType(typeof(DateTime), DbType.Time)); 61 | list.Add(new Type2DbType(typeof(TimeSpan), DbType.Time)); 62 | 63 | list.Add(new Type2DbType(typeof(Guid), DbType.Guid)); 64 | list.Add(new Type2DbType(typeof(Object), DbType.Object)); 65 | list.Add(new Type2DbType(typeof(Byte[]), DbType.Binary)); 66 | list.Add(new Type2DbType(typeof(Object), DbType.Object)); 67 | 68 | return list; 69 | } 70 | } 71 | 72 | /// 73 | internal class Type2DbType 74 | { 75 | /// 76 | public Type2DbType(Type type, DbType dbType) 77 | { 78 | Type = type; 79 | DbType = dbType; 80 | } 81 | 82 | /// 83 | public Type Type { get; } 84 | /// 85 | public DbType DbType { get; } 86 | } 87 | } 88 | -------------------------------------------------------------------------------- /DbMocker/Helpers/DbTypeSchemaDescriptor.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Data; 3 | 4 | namespace Apps72.Dev.Data.DbMocker.Helpers 5 | { 6 | /// 7 | internal class DbTypeSchemaDescriptor 8 | { 9 | /// 10 | internal DbTypeSchemaDescriptor(DbType dbType, int columnSize, object numericPrecision, object numericScale) 11 | { 12 | DbType = dbType; 13 | ColumnSize = columnSize; 14 | NumericPrecision = numericPrecision; 15 | NumericScale = numericScale; 16 | } 17 | 18 | /// 19 | public DbType DbType { get; } 20 | 21 | /// 22 | public int ColumnSize { get; } 23 | 24 | /// 25 | public object NumericPrecision { get; } 26 | 27 | /// 28 | public object NumericScale { get; } 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /DbMocker/Helpers/MockDataReaderSchemaTableBuilder.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Data; 4 | using System.Data.Common; 5 | using System.Globalization; 6 | 7 | namespace Apps72.Dev.Data.DbMocker.Helpers 8 | { 9 | /// 10 | internal static class MockDataReaderSchemaTableBuilder 11 | { 12 | private static readonly Dictionary _dbTypeDescriptors = InitalizeDbTypeDescriptor(); 13 | 14 | /// 15 | internal static DataTable BuildSchema(MockColumn[] columns, object[,] rows) 16 | { 17 | DataRow row; 18 | DataTable schemaTable = new DataTable("SchemaTable"); 19 | 20 | schemaTable.Locale = CultureInfo.InvariantCulture; 21 | schemaTable.Columns.Add(SchemaTableColumn.ColumnName, typeof(string)); 22 | schemaTable.Columns.Add(SchemaTableColumn.ColumnOrdinal, typeof(int)); 23 | schemaTable.Columns.Add(SchemaTableColumn.ColumnSize, typeof(int)); 24 | schemaTable.Columns.Add(SchemaTableColumn.NumericPrecision, typeof(int)); 25 | schemaTable.Columns.Add(SchemaTableColumn.NumericScale, typeof(int)); 26 | schemaTable.Columns.Add(SchemaTableColumn.IsUnique, typeof(bool)); 27 | schemaTable.Columns.Add(SchemaTableColumn.IsKey, typeof(bool)); 28 | schemaTable.Columns.Add(SchemaTableOptionalColumn.BaseServerName, typeof(string)); 29 | schemaTable.Columns.Add(SchemaTableOptionalColumn.BaseCatalogName, typeof(string)); 30 | schemaTable.Columns.Add(SchemaTableColumn.BaseColumnName, typeof(string)); 31 | schemaTable.Columns.Add(SchemaTableColumn.BaseSchemaName, typeof(string)); 32 | schemaTable.Columns.Add(SchemaTableColumn.BaseTableName, typeof(string)); 33 | schemaTable.Columns.Add(SchemaTableColumn.DataType, typeof(Type)); 34 | schemaTable.Columns.Add(SchemaTableColumn.AllowDBNull, typeof(bool)); 35 | schemaTable.Columns.Add(SchemaTableColumn.ProviderType, typeof(int)); 36 | schemaTable.Columns.Add(SchemaTableColumn.IsAliased, typeof(bool)); 37 | schemaTable.Columns.Add(SchemaTableColumn.IsExpression, typeof(bool)); 38 | schemaTable.Columns.Add(SchemaTableOptionalColumn.IsAutoIncrement, typeof(bool)); 39 | schemaTable.Columns.Add(SchemaTableOptionalColumn.IsRowVersion, typeof(bool)); 40 | schemaTable.Columns.Add(SchemaTableOptionalColumn.IsHidden, typeof(bool)); 41 | schemaTable.Columns.Add(SchemaTableColumn.IsLong, typeof(bool)); 42 | schemaTable.Columns.Add(SchemaTableOptionalColumn.IsReadOnly, typeof(Boolean)); 43 | schemaTable.Columns.Add(SchemaTableOptionalColumn.ProviderSpecificDataType, typeof(Type)); 44 | schemaTable.Columns.Add(SchemaTableOptionalColumn.DefaultValue, typeof(object)); 45 | 46 | schemaTable.BeginLoadData(); 47 | 48 | for (int i = 0; i < columns.Length; i++) 49 | { 50 | var column = columns[i]; 51 | row = schemaTable.NewRow(); 52 | 53 | bool canGetTypeFromFirstRow = rows.GetLength(0) > 0 && rows.GetLength(1) > i && rows[0, i] != null; 54 | Type columnType = (column.Type == typeof(object) && canGetTypeFromFirstRow) ? rows[0, i].GetType() : column.Type; 55 | Type rawColumType = GetFieldType(columnType); 56 | DbType dbColumType = DbTypeMap.FirstDbType(rawColumType); 57 | DbTypeSchemaDescriptor dbTypeDescriptor = GetDbTyeDescriptor(dbColumType); 58 | 59 | row[SchemaTableColumn.ColumnName] = column.Name; 60 | row[SchemaTableColumn.BaseColumnName] = column.Name; 61 | row[SchemaTableColumn.ColumnOrdinal] = i; 62 | row[SchemaTableColumn.ColumnSize] = dbTypeDescriptor.ColumnSize; 63 | row[SchemaTableColumn.NumericPrecision] = dbTypeDescriptor.NumericPrecision; 64 | row[SchemaTableColumn.NumericScale] = dbTypeDescriptor.NumericScale; 65 | row[SchemaTableColumn.ProviderType] = dbTypeDescriptor.DbType; 66 | row[SchemaTableColumn.AllowDBNull] = IsNullable(columnType); 67 | 68 | row[SchemaTableColumn.IsUnique] = false; 69 | row[SchemaTableOptionalColumn.IsReadOnly] = false; 70 | row[SchemaTableOptionalColumn.IsRowVersion] = false; 71 | row[SchemaTableOptionalColumn.IsAutoIncrement] = false; 72 | row[SchemaTableColumn.DataType] = rawColumType; 73 | row[SchemaTableOptionalColumn.IsHidden] = false; 74 | row[SchemaTableColumn.BaseSchemaName] = column.Name; 75 | 76 | 77 | row[SchemaTableColumn.IsExpression] = false; 78 | row[SchemaTableColumn.IsAliased] = false; 79 | 80 | row[SchemaTableColumn.BaseTableName] = DBNull.Value; 81 | row[SchemaTableOptionalColumn.BaseCatalogName] = DBNull.Value; 82 | 83 | schemaTable.Rows.Add(row); 84 | } 85 | 86 | schemaTable.AcceptChanges(); 87 | schemaTable.EndLoadData(); 88 | 89 | return schemaTable; 90 | } 91 | 92 | /// 93 | private static bool IsNullable(Type type) 94 | { 95 | if (!type.IsValueType) 96 | return true; // ref-type 97 | 98 | if (Nullable.GetUnderlyingType(type) != null) 99 | return true; // Nullable 100 | 101 | return false; // value-type 102 | } 103 | 104 | /// 105 | private static Type GetFieldType(Type type) 106 | { 107 | if (!type.IsValueType) 108 | return type; 109 | 110 | Type nullableType = Nullable.GetUnderlyingType(type); 111 | if (nullableType != null) 112 | return nullableType; 113 | 114 | return type; 115 | } 116 | 117 | /// 118 | private static DbTypeSchemaDescriptor GetDbTyeDescriptor(DbType dbType) 119 | { 120 | if (_dbTypeDescriptors.ContainsKey(dbType)) 121 | return _dbTypeDescriptors[dbType]; 122 | 123 | return _dbTypeDescriptors[DbType.Object]; 124 | } 125 | 126 | /// 127 | private static Dictionary InitalizeDbTypeDescriptor() 128 | { 129 | var dbTypeDescriptors = new Dictionary() 130 | { 131 | [DbType.AnsiString] = new DbTypeSchemaDescriptor(DbType.AnsiString, int.MaxValue, DBNull.Value, DBNull.Value), 132 | [DbType.Binary] = new DbTypeSchemaDescriptor(DbType.Binary, int.MaxValue, DBNull.Value, DBNull.Value), 133 | [DbType.Byte] = new DbTypeSchemaDescriptor(DbType.Byte, 1, 3, 0), 134 | [DbType.Boolean] = new DbTypeSchemaDescriptor(DbType.Boolean, 1, DBNull.Value, DBNull.Value), 135 | [DbType.Currency] = new DbTypeSchemaDescriptor(DbType.Currency, 8, 19, 4), 136 | [DbType.Date] = new DbTypeSchemaDescriptor(DbType.Date, 8, DBNull.Value, DBNull.Value), 137 | [DbType.DateTime] = new DbTypeSchemaDescriptor(DbType.DateTime, 8, DBNull.Value, DBNull.Value), 138 | [DbType.Decimal] = new DbTypeSchemaDescriptor(DbType.Decimal, 8, 53, DBNull.Value), 139 | [DbType.Double] = new DbTypeSchemaDescriptor(DbType.Double, 8, 53, DBNull.Value), 140 | [DbType.Guid] = new DbTypeSchemaDescriptor(DbType.Guid, 16, DBNull.Value, DBNull.Value), 141 | [DbType.Int16] = new DbTypeSchemaDescriptor(DbType.Int16, 2, 5, 0), 142 | [DbType.Int32] = new DbTypeSchemaDescriptor(DbType.Int32, 4, 10, 0), 143 | [DbType.Int64] = new DbTypeSchemaDescriptor(DbType.Int64, 8, 19, 0), 144 | [DbType.Object] = new DbTypeSchemaDescriptor(DbType.Object, int.MaxValue, DBNull.Value, DBNull.Value), 145 | [DbType.SByte] = new DbTypeSchemaDescriptor(DbType.SByte, 1, 3, 0), 146 | [DbType.Single] = new DbTypeSchemaDescriptor(DbType.Single, 4, 24, DBNull.Value), 147 | [DbType.String] = new DbTypeSchemaDescriptor(DbType.String, int.MaxValue, DBNull.Value, DBNull.Value), 148 | [DbType.Time] = new DbTypeSchemaDescriptor(DbType.Time, 8, DBNull.Value, DBNull.Value), 149 | [DbType.UInt16] = new DbTypeSchemaDescriptor(DbType.UInt16, 2, 5, 0), 150 | [DbType.UInt32] = new DbTypeSchemaDescriptor(DbType.UInt32, 4, 10, 0), 151 | [DbType.UInt64] = new DbTypeSchemaDescriptor(DbType.UInt64, 8, 19, 0), 152 | [DbType.VarNumeric] = new DbTypeSchemaDescriptor(DbType.VarNumeric, 8, 53, 0), 153 | [DbType.AnsiStringFixedLength] = new DbTypeSchemaDescriptor(DbType.AnsiStringFixedLength, int.MaxValue, DBNull.Value, DBNull.Value), 154 | [DbType.StringFixedLength] = new DbTypeSchemaDescriptor(DbType.StringFixedLength, int.MaxValue, DBNull.Value, DBNull.Value), 155 | [DbType.Xml] = new DbTypeSchemaDescriptor(DbType.Xml, int.MaxValue, DBNull.Value, DBNull.Value), 156 | [DbType.DateTime2] = new DbTypeSchemaDescriptor(DbType.DateTime2, 8, DBNull.Value, DBNull.Value), 157 | [DbType.DateTimeOffset] = new DbTypeSchemaDescriptor(DbType.DateTimeOffset, 8, DBNull.Value, DBNull.Value) 158 | }; 159 | 160 | return dbTypeDescriptors; 161 | } 162 | } 163 | } 164 | -------------------------------------------------------------------------------- /DbMocker/Helpers/TypeExtension.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Linq; 3 | 4 | namespace Apps72.Dev.Data.DbMocker.Helpers 5 | { 6 | /// 7 | internal static class TypeExtension 8 | { 9 | /// 10 | /// Returns True if this object is a simple type. 11 | /// See https://msdn.microsoft.com/en-us/library/system.type.isprimitive.aspx 12 | /// 13 | /// 14 | /// 15 | public static bool IsPrimitive(this Type type) 16 | { 17 | return type == typeof(DateTime) || type == typeof(Nullable) || 18 | type == typeof(Decimal) || type == typeof(Nullable) || 19 | type == typeof(String) || 20 | type == typeof(Boolean) || type == typeof(Nullable) || 21 | type == typeof(Byte) || type == typeof(Nullable) || 22 | type == typeof(SByte) || type == typeof(Nullable) || 23 | type == typeof(Int16) || type == typeof(Nullable) || 24 | type == typeof(UInt16) || type == typeof(Nullable) || 25 | type == typeof(Int32) || type == typeof(Nullable) || 26 | type == typeof(UInt32) || type == typeof(Nullable) || 27 | type == typeof(Int64) || type == typeof(Nullable) || 28 | type == typeof(UInt64) || type == typeof(Nullable) || 29 | type == typeof(IntPtr) || type == typeof(Nullable) || 30 | type == typeof(UIntPtr) || type == typeof(Nullable) || 31 | type == typeof(Char) || type == typeof(Nullable) || 32 | type == typeof(Double) || type == typeof(Nullable) || 33 | type == typeof(Single) || type == typeof(Nullable); 34 | } 35 | 36 | /// 37 | /// Convert the string to a equivalent datatype. Or null if not found. 38 | /// 39 | /// 40 | /// 41 | public static Type NameToType(this string value) 42 | { 43 | Type result = Type.GetType(value, throwOnError: false, ignoreCase: true); 44 | 45 | if (result != null) 46 | { 47 | return result; 48 | } 49 | else 50 | { 51 | switch (value.Trim().ToLower()) 52 | { 53 | case "datetime": 54 | case "smalldatetime": 55 | case "date": 56 | return typeof(DateTime); 57 | 58 | case "time": 59 | case "timespan": 60 | return typeof(TimeSpan); 61 | 62 | case "guid": 63 | case "id": 64 | case "uniqueidentifier": 65 | case "unique": 66 | return typeof(Guid); 67 | 68 | case "decimal": 69 | return typeof(decimal); 70 | 71 | case "double": 72 | return typeof(double); 73 | 74 | case "single": 75 | case "float": 76 | return typeof(float); 77 | 78 | case "string": 79 | case "varchar": 80 | case "nvarchar": 81 | return typeof(string); 82 | 83 | case "char": 84 | case "nchar": 85 | return typeof(char); 86 | 87 | case "boolean": 88 | case "bool": 89 | return typeof(bool); 90 | 91 | case "byte": 92 | return typeof(byte); 93 | 94 | case "sbyte": 95 | return typeof(sbyte); 96 | 97 | case "int16": 98 | case "short": 99 | return typeof(short); 100 | 101 | case "uint16": 102 | case "ushort": 103 | return typeof(ushort); 104 | 105 | case "int32": 106 | case "int": 107 | return typeof(int); 108 | 109 | case "uint32": 110 | case "uint": 111 | return typeof(uint); 112 | 113 | case "int64": 114 | case "long": 115 | return typeof(long); 116 | 117 | case "uint64": 118 | case "ulong": 119 | return typeof(ulong); 120 | 121 | default: 122 | return null; 123 | } 124 | } 125 | 126 | } 127 | 128 | /// 129 | /// Convert the string to a equivalent datatype. Or null if not found. 130 | /// 131 | /// 132 | /// 133 | public static object ConvertToType(this string value) 134 | { 135 | return (T)Convert.ChangeType(value, typeof(T)); 136 | } 137 | 138 | /// 139 | /// Returns the best data type infered from the value text. 140 | /// 141 | /// 142 | /// 143 | public static Type BestType(this string text) 144 | { 145 | if (DateTime.TryParse(text, out DateTime _)) return typeof(DateTime); 146 | if (Boolean.TryParse(text, out Boolean _)) return typeof(Boolean); 147 | if (Int32.TryParse(text, out Int32 _)) return typeof(Int32); 148 | if (Int64.TryParse(text, out Int64 _)) return typeof(Int64); 149 | if (Double.TryParse(text, out Double _)) return typeof(Double); 150 | if (Decimal.TryParse(text, out Decimal _)) return typeof(Decimal); 151 | if (Char.TryParse(text, out Char _)) return typeof(Char); 152 | return typeof(string); 153 | } 154 | 155 | /// 156 | /// Keep Only letters, to convert " (int) " to "int". 157 | /// 158 | /// 159 | /// 160 | public static string KeepOnlyLetters(this string value) 161 | { 162 | return new String(value.Where(Char.IsLetter).ToArray()).Trim(); 163 | } 164 | } 165 | } 166 | -------------------------------------------------------------------------------- /DbMocker/MockColumn.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Diagnostics; 3 | using System.Linq; 4 | 5 | namespace Apps72.Dev.Data.DbMocker 6 | { 7 | /// 8 | [DebuggerDisplay("{" + nameof(Name) + "}")] 9 | public class MockColumn 10 | { 11 | /// 12 | public MockColumn() : this(string.Empty, typeof(object)) 13 | { 14 | } 15 | 16 | /// 17 | public MockColumn(string name) : this(name, typeof(object)) 18 | { 19 | } 20 | 21 | /// 22 | public MockColumn(string name, Type type) 23 | { 24 | this.Name = name; 25 | this.Type = type; 26 | } 27 | 28 | /// 29 | public string Name { get; set; } 30 | 31 | /// 32 | public Type Type { get; set; } 33 | 34 | /// 35 | public static implicit operator string(MockColumn column) 36 | { 37 | return column.Name; 38 | } 39 | 40 | /// 41 | public static implicit operator MockColumn(string name) 42 | { 43 | return new MockColumn() 44 | { 45 | Name = name, 46 | Type = typeof(object) 47 | }; 48 | } 49 | 50 | /// 51 | public static implicit operator (string Name, Type Type)(MockColumn column) 52 | { 53 | return (column.Name, column.Type); 54 | } 55 | 56 | /// 57 | public static implicit operator MockColumn((string Name, Type Type) column) 58 | { 59 | return new MockColumn() 60 | { 61 | Name = column.Name, 62 | Type = column.Type 63 | }; 64 | } 65 | } 66 | 67 | public static class Columns 68 | { 69 | public static MockColumn[] WithNames(params string[] names) 70 | { 71 | return names.Select(name => new MockColumn(name)).ToArray(); 72 | } 73 | 74 | public static MockColumn[] WithNames(params (string Name, Type Type)[] columns) 75 | { 76 | return columns.Select(i => new MockColumn(i.Name, i.Type)).ToArray(); 77 | } 78 | } 79 | } 80 | -------------------------------------------------------------------------------- /DbMocker/MockCommand.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Data.Common; 4 | using System.Linq; 5 | 6 | namespace Apps72.Dev.Data.DbMocker 7 | { 8 | /// 9 | public class MockCommand 10 | { 11 | /// 12 | internal MockCommand(Data.MockDbCommand command) 13 | { 14 | this.CommandText = command.CommandText; 15 | this.Parameters = command.Parameters.Cast(); 16 | } 17 | 18 | /// 19 | public string CommandText { get; set; } 20 | 21 | /// 22 | public IEnumerable Parameters { get; set; } 23 | 24 | /// 25 | public bool HasValidSqlServerCommandText() 26 | { 27 | var parseErrors = Microsoft.SqlServer.Management.SqlParser.Parser.Parser.Parse(this.CommandText); 28 | var hasError = parseErrors.Errors.Any(err => err.IsWarning == false); 29 | if (hasError) 30 | { 31 | var errorStrings = parseErrors.Errors 32 | .Where(err => err.IsWarning == false) 33 | .Select(err => $"{err.Start}. {err.Message}"); 34 | 35 | var innerException = new Exception(String.Join(Environment.NewLine, errorStrings)); 36 | 37 | throw new MockException("DbMocker failed. The CommandText is not a valid SQL Server query.", 38 | innerException) 39 | { 40 | CommandText = this.CommandText, 41 | Parameters = this.Parameters, 42 | }; 43 | } 44 | else 45 | { 46 | return true; 47 | } 48 | 49 | } 50 | } 51 | } 52 | -------------------------------------------------------------------------------- /DbMocker/MockConditions.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Reflection; 5 | 6 | namespace Apps72.Dev.Data.DbMocker 7 | { 8 | /// 9 | public class MockConditions 10 | { 11 | internal bool MustValidateSqlServerCommandText = false; 12 | private List _conditions = new List(); 13 | 14 | /// 15 | internal MockConditions(MockDbConnection connection) 16 | { 17 | 18 | } 19 | 20 | /// 21 | /// Gets all conditions recorded. 22 | /// 23 | public IEnumerable Conditions => _conditions; 24 | 25 | /// 26 | /// Add a condition to return mock data. 27 | /// 28 | /// 29 | /// 30 | public MockReturns When(Func condition) 31 | { 32 | return WhenPrivate($"When([Expression])", condition); 33 | } 34 | 35 | /// 36 | /// Add a condition to return mock data, when the is detected. 37 | /// 38 | /// 39 | /// 40 | public MockReturns WhenTag(string tagName) 41 | { 42 | return WhenPrivate( 43 | description: $"WhenTag({tagName})", 44 | condition: (cmd) => 45 | { 46 | string toSearch = $"-- {tagName}"; 47 | var lines = cmd.CommandText 48 | .Split(MockTable.SPLIT_NEWLINE, StringSplitOptions.RemoveEmptyEntries); 49 | return lines.Any(line => line.TrimEnd() == toSearch); 50 | }); 51 | } 52 | 53 | /// 54 | /// Load all Embedded resource "[TagName].txt" with Fixed format. 55 | /// And add it as method. 56 | /// 57 | /// 58 | /// 59 | public void LoadTagsFromResources(params string[] fileNames) 60 | { 61 | this.LoadTagsFromResources(Assembly.GetCallingAssembly(), fileNames); 62 | } 63 | 64 | /// 65 | /// Load all Embedded resource "[TagName].txt" with Fixed format. 66 | /// And add it as method. 67 | /// 68 | /// 69 | /// 70 | public void LoadTagsFromResources(Assembly assembly, params string[] fileNames) 71 | { 72 | string[] allResources = assembly.GetManifestResourceNames(); 73 | 74 | foreach (var filename in fileNames) 75 | { 76 | string resourceName = allResources.FirstOrDefault(i => i.EndsWith($".{filename}.{MockResourceOptions.Extension}", StringComparison.OrdinalIgnoreCase)); 77 | 78 | if (!string.IsNullOrEmpty(resourceName)) 79 | { 80 | // Split the filename to "[Identifier]-[TagName]" 81 | string[] resourceNameParts = filename.Split(new[] { MockResourceOptions.TagSeparator }, StringSplitOptions.RemoveEmptyEntries); 82 | string tagName = resourceNameParts.Length == 2 ? resourceNameParts[1] : filename; 83 | 84 | this.WhenTag(tagName) 85 | .ReturnsTable(MockTable.FromFixed(assembly, resourceName)); 86 | } 87 | } 88 | } 89 | 90 | /// 91 | /// Catch all SQL queries to returns always the same mock data. 92 | /// 93 | /// 94 | public MockReturns WhenAny() 95 | { 96 | return WhenPrivate("WhenAny()", null); 97 | } 98 | 99 | /// 100 | /// Check if queries have correct SQL Server syntax. 101 | /// 102 | /// 103 | public MockConditions HasValidSqlServerCommandText() 104 | { 105 | return HasValidSqlServerCommandText(toValidate: true); 106 | } 107 | 108 | /// 109 | /// Check if queries have correct SQL Server syntax. 110 | /// 111 | /// To validate or not, the SQL queries. 112 | /// 113 | public MockConditions HasValidSqlServerCommandText(bool toValidate) 114 | { 115 | MustValidateSqlServerCommandText = toValidate; 116 | return this; 117 | } 118 | 119 | /// 120 | internal MockTable[] GetFirstMockTablesFound(MockCommand command) 121 | { 122 | foreach (MockReturns item in _conditions) 123 | { 124 | if (item.Condition.Invoke(command) == true) 125 | { 126 | return item.ReturnsFunction(command); 127 | } 128 | } 129 | 130 | throw new MockException("No mock found. Use MockDbConnection.Mocks.Where(...).Returns(...) methods to define mocks.") 131 | { 132 | CommandText = command.CommandText, 133 | Parameters = command.Parameters 134 | }; 135 | } 136 | 137 | /// 138 | /// Add a condition to return mock data. 139 | /// 140 | /// Label to identify the condition 141 | /// Function to execute 142 | /// 143 | private MockReturns WhenPrivate(string description, Func condition) 144 | { 145 | if (condition == null) 146 | { 147 | condition = (cmd => true); 148 | } 149 | 150 | var mock = new MockReturns() 151 | { 152 | Description = description, 153 | Condition = (cmd) => 154 | { 155 | if (MustValidateSqlServerCommandText) 156 | { 157 | return condition.Invoke(cmd) && cmd.HasValidSqlServerCommandText(); 158 | } 159 | else 160 | { 161 | return condition.Invoke(cmd); 162 | } 163 | } 164 | }; 165 | _conditions.Add(mock); 166 | return mock; 167 | } 168 | 169 | } 170 | } 171 | -------------------------------------------------------------------------------- /DbMocker/MockDbConnection.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Data; 3 | using System.Data.Common; 4 | 5 | namespace Apps72.Dev.Data.DbMocker 6 | { 7 | /// 8 | public class MockDbConnection : DbConnection 9 | { 10 | private ConnectionState _connectionState = ConnectionState.Closed; 11 | 12 | /// 13 | public MockDbConnection() 14 | { 15 | this.Mocks = new MockConditions(this); 16 | } 17 | 18 | /// 19 | /// Gets the list of database mocks. 20 | /// 21 | public MockConditions Mocks { get; private set; } 22 | 23 | /// 24 | /// Gets or sets the default value to validate queries (CommandText). 25 | /// 26 | public bool HasValidSqlServerCommandText 27 | { 28 | get 29 | { 30 | return this.Mocks.MustValidateSqlServerCommandText; 31 | } 32 | set 33 | { 34 | this.Mocks.MustValidateSqlServerCommandText = value; 35 | } 36 | } 37 | 38 | #region LEGACY METHODS 39 | 40 | /// 41 | public override string ConnectionString { get; set; } = "Server=DbMockerServer;Database=DbMockerDatabase"; 42 | 43 | /// 44 | public override string Database => "DbMockerDatabase"; 45 | 46 | /// 47 | public override string DataSource => "DbMockerServer"; 48 | 49 | /// 50 | public override string ServerVersion => "1.0"; 51 | 52 | /// 53 | public override ConnectionState State { get { return _connectionState; } } 54 | 55 | internal DbTransaction Transaction { get; set; } 56 | 57 | /// 58 | public override void ChangeDatabase(string databaseName) 59 | { 60 | } 61 | 62 | /// 63 | public override void Close() 64 | { 65 | _connectionState = ConnectionState.Closed; 66 | } 67 | 68 | /// 69 | public override void Open() 70 | { 71 | _connectionState = ConnectionState.Open; 72 | } 73 | 74 | /// 75 | protected override void Dispose(bool disposing) 76 | { 77 | Close(); 78 | base.Dispose(disposing); 79 | } 80 | 81 | /// 82 | protected override DbTransaction BeginDbTransaction(IsolationLevel isolationLevel) 83 | { 84 | if (this.Transaction == null) 85 | this.Transaction = new Data.MockDbTransaction(this); 86 | 87 | return this.Transaction; 88 | } 89 | 90 | /// 91 | protected override DbCommand CreateDbCommand() 92 | { 93 | return new Data.MockDbCommand(this); 94 | } 95 | 96 | public override DataTable GetSchema() 97 | { 98 | return this.GetSchema(null, null); 99 | } 100 | 101 | public override DataTable GetSchema(string collectionName) 102 | { 103 | return this.GetSchema(null, null); 104 | } 105 | 106 | public override DataTable GetSchema(string collectionName, string[] restrictionValues) 107 | { 108 | var table = new DataTable("DbMockerSchema"); 109 | 110 | table.Columns.AddRange(new[] 111 | { 112 | new DataColumn("DataType", typeof(string)), 113 | new DataColumn("TypeName", typeof(string)), 114 | new DataColumn("ProviderDbType", typeof(string)), 115 | }); 116 | 117 | table.Rows.Add("System.Byte[]", "binary", "1"); 118 | table.Rows.Add("System.Byte", "tinyint", "2"); 119 | table.Rows.Add("System.Boolean", "bit", "3"); 120 | table.Rows.Add("System.Guid", "uniqueidentifier", "4"); 121 | table.Rows.Add("System.DateTime", "datetime", "6"); 122 | table.Rows.Add("System.Decimal", "numeric", "7"); 123 | table.Rows.Add("System.Double", "float", "8"); 124 | table.Rows.Add("System.Int16", "smallint", "10"); 125 | table.Rows.Add("System.Int32", "int", "11"); 126 | table.Rows.Add("System.Int64", "bigint", "12"); 127 | table.Rows.Add("System.Single", "single", "15"); 128 | table.Rows.Add("System.String", "varchar", "16"); 129 | 130 | return table; 131 | } 132 | 133 | #endregion 134 | } 135 | } 136 | -------------------------------------------------------------------------------- /DbMocker/MockException.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Data.Common; 4 | 5 | namespace Apps72.Dev.Data.DbMocker 6 | { 7 | /// 8 | /// Exception raised when a Mock is not defined. 9 | /// 10 | public class MockException : ApplicationException 11 | { 12 | // 13 | // Summary: 14 | // Initializes a new instance of the System.ApplicationException class. 15 | public MockException() 16 | : base() { } 17 | 18 | // 19 | // Summary: 20 | // Initializes a new instance of the System.ApplicationException class with a specified 21 | // error message. 22 | // 23 | // Parameters: 24 | // message: 25 | // A message that describes the error. 26 | public MockException(string message) 27 | : base(message) { } 28 | 29 | // 30 | // Summary: 31 | // Initializes a new instance of the System.ApplicationException class with a specified 32 | // error message and a reference to the inner exception that is the cause of this 33 | // exception. 34 | // 35 | // Parameters: 36 | // message: 37 | // The error message that explains the reason for the exception. 38 | // 39 | // innerException: 40 | // The exception that is the cause of the current exception. If the innerException 41 | // parameter is not a null reference, the current exception is raised in a catch 42 | // block that handles the inner exception. 43 | public MockException(string message, Exception innerException) 44 | : base(message, innerException) { } 45 | 46 | /// 47 | /// SQL Query which generate the exception. 48 | /// 49 | public string CommandText { get; internal set; } 50 | 51 | /// 52 | /// List of parameters used by the SQL Query which generate the exception. 53 | /// 54 | public IEnumerable Parameters { get; internal set; } 55 | } 56 | } 57 | -------------------------------------------------------------------------------- /DbMocker/MockResourceOptions.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | 3 | namespace Apps72.Dev.Data.DbMocker 4 | { 5 | /// 6 | public static class MockResourceOptions 7 | { 8 | /// 9 | /// Gets or sets the separator used to split Resource name to Tag and multiple-resources. 10 | /// 11 | public static string TagSeparator { get; set; } = "-"; 12 | 13 | /// 14 | /// Gets or sets the extension of resources 15 | /// 16 | public static string Extension { get; set; } = "txt"; 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /DbMocker/MockReturns.cs: -------------------------------------------------------------------------------- 1 | using Apps72.Dev.Data.DbMocker.Helpers; 2 | using System; 3 | using System.Collections.Generic; 4 | using System.Data; 5 | using System.Linq; 6 | using System.Reflection; 7 | 8 | namespace Apps72.Dev.Data.DbMocker 9 | { 10 | /// 11 | [System.Diagnostics.DebuggerDisplay("{Description}")] 12 | public class MockReturns 13 | { 14 | /// 15 | /// Gets the Description of this condition. 16 | /// 17 | public string Description { get; internal set; } 18 | 19 | /// 20 | private List> _modifyParameter = new List>(); 21 | 22 | private Func _returnsFunction; 23 | 24 | private readonly List> _callbacks = new List>(); 25 | 26 | /// 27 | internal Func ReturnsFunction 28 | { 29 | get 30 | { 31 | return (command) => 32 | { 33 | foreach (Action callback in _callbacks) 34 | { 35 | callback(command); 36 | } 37 | 38 | foreach (var mody in _modifyParameter) 39 | { 40 | mody(command); 41 | } 42 | 43 | return _returnsFunction(command); 44 | }; 45 | } 46 | set 47 | { 48 | _returnsFunction = value; 49 | } 50 | } 51 | 52 | /// 53 | internal Func Condition { get; set; } 54 | 55 | /// 56 | /// Sets the expression to return a multiple result set, presented by an array of 57 | /// with sample data, when the condition occured. 58 | /// 59 | /// Method or Lambda expression to return a 60 | public void ReturnsDataset(params MockTable[] returns) 61 | { 62 | ReturnsFunction = (cmd) => returns; 63 | } 64 | 65 | /// 66 | /// Sets the expression to return a multiple result set, presented by an array of 67 | /// with sample data, when the condition occured. 68 | /// 69 | /// Method or Lambda expression to return a 70 | public void ReturnsDataset(Func returns) 71 | { 72 | ReturnsFunction = returns; 73 | } 74 | 75 | /// 76 | /// Sets the expression to return a with sample data, when the condition occured. 77 | /// 78 | /// Method or Lambda expression to return a 79 | public void ReturnsTable(Func returns) 80 | { 81 | ReturnsFunction = (cmd) => new[] { returns.Invoke(cmd) }; 82 | } 83 | 84 | /// 85 | /// Sets with sample data, when the condition occured. 86 | /// 87 | /// with sample data 88 | public void ReturnsTable(MockTable returns) 89 | { 90 | ReturnsFunction = (cmd) => new[] { returns }; 91 | } 92 | 93 | /// 94 | /// Sets the expression to return a sample data object, when the condition occured. 95 | /// This object is converted to a where columns are property names 96 | /// and data in the first row are proerty values. 97 | /// 98 | /// Sample data 99 | public void ReturnsRow(Func returns) 100 | { 101 | ReturnsFunction = (cmd) => ConvertToMockTables(returns.Invoke(cmd)); 102 | } 103 | 104 | /// 105 | /// Sets a sample data object, when the condition occured. 106 | /// This object is converted to a where columns are property names 107 | /// and data in the first row are proerty values. 108 | /// 109 | /// Sample data 110 | public void ReturnsRow(T returns) 111 | { 112 | ReturnsFunction = (cmd) => ConvertToMockTables(returns); 113 | } 114 | 115 | /// 116 | /// Sets with sample data, when the condition occured. 117 | /// 118 | /// with sample data 119 | public void ReturnsRow(MockTable returns) 120 | { 121 | ReturnsFunction = (cmd) => new[] { returns }; 122 | } 123 | 124 | /// 125 | /// Throws the specified exception. 126 | /// 127 | /// The exception. 128 | public void ThrowsException(Exception exception) 129 | { 130 | ReturnsFunction = command => throw exception; 131 | } 132 | 133 | /// 134 | /// Throws the specified exception type. 135 | /// 136 | /// The type of the exception. 137 | public void ThrowsException() where TException : Exception, new() 138 | { 139 | ReturnsFunction = command => throw new TException(); 140 | } 141 | 142 | /// 143 | /// Set output value for dbParameter, when the condition occured. 144 | /// 145 | /// Value to return 146 | public MockReturns SetParameterValue(string parameterName, object value, ParameterDirection direction = ParameterDirection.Output) 147 | { 148 | _modifyParameter.Add((command) => 149 | { 150 | var parameter = command.Parameters.FirstOrDefault(a => a.ParameterName == parameterName); 151 | 152 | if (parameter == null) 153 | { 154 | throw new MockException($"parameterName '{parameterName}' doesn't find"); 155 | } 156 | 157 | if (parameter.Direction != direction) 158 | { 159 | throw new MockException($"Actual direction parameter '{parameter.Direction.ToString()}' doesn't equels expected value '{direction}'"); 160 | } 161 | 162 | parameter.Value = value; 163 | }); 164 | 165 | return this; 166 | } 167 | 168 | /// 169 | /// Sets the expression to execute an action, to trace some data for example. 170 | /// 171 | /// 172 | /// 173 | public MockReturns Callback(Action callback) 174 | { 175 | if (callback != null) 176 | { 177 | _callbacks.Add(callback); 178 | } 179 | 180 | return this; 181 | } 182 | 183 | /// 184 | /// Sets the expression to return the value, when the condition occured. 185 | /// 186 | /// Value to return 187 | public void ReturnsScalar(Func returns) 188 | { 189 | if (returns == null) 190 | { 191 | ReturnsFunction = (cmd) => ConvertToMockTables(returns); 192 | } 193 | else 194 | { 195 | ReturnsFunction = (cmd) => ConvertToMockTables(returns.Invoke(cmd)); 196 | } 197 | } 198 | 199 | /// 200 | /// Sets the value to return when the condition occured. 201 | /// 202 | /// Value to return 203 | public void ReturnsScalar(T returns) 204 | { 205 | ReturnsFunction = (cmd) => ConvertToMockTables(returns); 206 | } 207 | 208 | /// 209 | private MockTable[] ConvertToMockTables(T returns) 210 | { 211 | return new[] { ConvertToMockTable(returns) }; 212 | } 213 | 214 | /// 215 | private MockTable ConvertToMockTable(T returns) 216 | { 217 | if (returns == null || returns is DBNull || typeof(T).IsPrimitive()) 218 | { 219 | return new MockTable() 220 | { 221 | Columns = Columns.WithNames(string.Empty), 222 | Rows = new object[,] 223 | { 224 | { returns } 225 | } 226 | }; 227 | } 228 | else 229 | { 230 | Type type = typeof(T); 231 | PropertyInfo[] properties = type.GetProperties(BindingFlags.Public | BindingFlags.Instance); 232 | var columns = new List(); 233 | var values = new List(); 234 | 235 | foreach (PropertyInfo property in properties) 236 | { 237 | columns.Add(property.Name); 238 | values.Add(GetValueOrDbNull(property.GetValue(returns))); 239 | } 240 | 241 | return new MockTable(columns.ToArray(), 242 | new object[][] { values.ToArray() }.ToTwoDimensionalArray()); 243 | } 244 | } 245 | 246 | /// 247 | private object GetValueOrDbNull(object value) 248 | { 249 | return value == null ? DBNull.Value : value; 250 | } 251 | } 252 | } 253 | -------------------------------------------------------------------------------- /DbMocker/MockTable.cs: -------------------------------------------------------------------------------- 1 | using Apps72.Dev.Data.DbMocker.Helpers; 2 | using System; 3 | using System.Collections.Generic; 4 | using System.Linq; 5 | 6 | namespace Apps72.Dev.Data.DbMocker 7 | { 8 | /// 9 | public partial class MockTable 10 | { 11 | public static readonly char[] SPLIT_NEWLINE = { '\r', '\n' }; 12 | private List _rows = new List(); 13 | 14 | /// 15 | public MockTable() 16 | { 17 | this.Columns = Array.Empty(); 18 | this.Rows = null; 19 | } 20 | 21 | /// 22 | public MockTable(string[] columns, object[,] rows) 23 | { 24 | this.Columns = columns.Select(name => new MockColumn(name)).ToArray(); 25 | this.Rows = rows; 26 | } 27 | 28 | /// 29 | public MockColumn[] Columns { get; set; } 30 | 31 | /// 32 | public object[,] Rows 33 | { 34 | get 35 | { 36 | return _rows.ToArray().ToTwoDimensionalArray(); 37 | } 38 | set 39 | { 40 | if (value == null) 41 | _rows = new List(); 42 | else 43 | _rows = new List(value.ToJaggedArray()); 44 | } 45 | } 46 | 47 | /// 48 | public MockTable AddRow(params object[] values) 49 | { 50 | _rows.Add(values); 51 | return this; 52 | } 53 | 54 | /// 55 | public MockTable AddColumns(params string[] columns) 56 | { 57 | this.Columns = this.Columns.Concat(DbMocker.Columns.WithNames(columns)).ToArray(); 58 | return this; 59 | } 60 | 61 | /// 62 | public MockTable AddColumns(params (string Name, Type Type)[] columns) 63 | { 64 | this.Columns = this.Columns.Concat(DbMocker.Columns.WithNames(columns)).ToArray(); 65 | return this; 66 | } 67 | 68 | /// 69 | internal object GetFirstColRowOrNull() 70 | { 71 | if (Rows != null && Rows.GetLength(0) > 0 && Rows.GetLength(1) > 0) 72 | return Rows[0, 0]; 73 | else 74 | return null; 75 | } 76 | 77 | } 78 | } 79 | -------------------------------------------------------------------------------- /DbMocker/MockTableFromType.cs: -------------------------------------------------------------------------------- 1 | using System.Collections.Generic; 2 | using System.Linq; 3 | using System.Reflection; 4 | 5 | namespace Apps72.Dev.Data.DbMocker 6 | { 7 | public partial class MockTable 8 | { 9 | public const BindingFlags DefaultFromTypeBindingFlags = BindingFlags.Instance | BindingFlags.GetProperty | BindingFlags.Public; 10 | 11 | /// 12 | public static MockTable FromType( 13 | IEnumerable rows = null, 14 | BindingFlags propertyBindingFlags = DefaultFromTypeBindingFlags, 15 | string[] columnsToInclude = null 16 | ) 17 | { 18 | var propertyInfos = typeof(T).GetProperties(propertyBindingFlags); 19 | 20 | var columns = propertyInfos 21 | .Where(propertyInfo => 22 | columnsToInclude == null || 23 | columnsToInclude.Length == 0 || 24 | columnsToInclude.Contains(propertyInfo.Name)) 25 | .Select(propertyInfo => (propertyInfo.Name, propertyInfo.PropertyType)) 26 | .ToArray(); 27 | 28 | var table = WithColumns(columns); 29 | 30 | if (rows != null) 31 | { 32 | foreach (var row in rows) 33 | { 34 | var values = propertyInfos 35 | .Select(pi => pi.GetValue(row)) 36 | .ToArray(); 37 | 38 | table.AddRow(values); 39 | } 40 | } 41 | 42 | return table; 43 | } 44 | } 45 | } 46 | -------------------------------------------------------------------------------- /DbMocker/MockTableImport.cs: -------------------------------------------------------------------------------- 1 | using Apps72.Dev.Data.DbMocker.Helpers; 2 | using System; 3 | using System.Collections.Generic; 4 | using System.Linq; 5 | using System.Reflection; 6 | 7 | namespace Apps72.Dev.Data.DbMocker 8 | { 9 | public partial class MockTable 10 | { 11 | /// 12 | public static MockTable FromCsv(string content, string delimiter, CsvImportOptions options) 13 | { 14 | var table = MockTable.Empty(); 15 | Type[] types = null; 16 | bool isFirstRow = true; // First row = Column names 17 | bool isFirstDataRow = false; // Second row = First data row 18 | bool mustRemoveEmptyLines = (options & CsvImportOptions.RemoveEmptyLines) == CsvImportOptions.RemoveEmptyLines; 19 | bool mustTrimLines = (options & CsvImportOptions.TrimLines) == CsvImportOptions.TrimLines; 20 | 21 | foreach (string row in content.Split(MockTable.SPLIT_NEWLINE, StringSplitOptions.None)) 22 | { 23 | if (mustRemoveEmptyLines && string.IsNullOrEmpty(row)) 24 | { 25 | 26 | } 27 | else 28 | { 29 | string[] data; 30 | string[] split_delimiter = new string[] { delimiter }; 31 | 32 | if (mustTrimLines) 33 | data = row.Trim().Split(split_delimiter, StringSplitOptions.None); 34 | else 35 | data = row.Split(split_delimiter, StringSplitOptions.None); 36 | 37 | if (isFirstRow) 38 | table.AddColumns(data); 39 | else 40 | { 41 | if (isFirstDataRow) 42 | types = GetTypesOfFirstDataRow(data); 43 | 44 | table.AddRow(ConvertStringToTypes(data, types)); 45 | } 46 | 47 | isFirstRow = false; 48 | isFirstDataRow = !isFirstDataRow ? true : isFirstDataRow; 49 | } 50 | } 51 | 52 | return table; 53 | } 54 | 55 | /// 56 | public static MockTable FromCsv(string content, string delimiter) 57 | { 58 | return FromCsv(content, delimiter, CsvImportOptions.RemoveEmptyLines | CsvImportOptions.TrimLines); 59 | } 60 | 61 | /// 62 | public static MockTable FromCsv(string content) 63 | { 64 | return FromCsv(content, "\t"); 65 | } 66 | 67 | /// 68 | public static MockTable FromFixed(string content) 69 | { 70 | return new MockTableImportFixed(content).GetMockTable(); 71 | } 72 | 73 | /// 74 | public static MockTable FromFixed(Assembly assembly, string resourceName) 75 | { 76 | return new MockTableImportFixed(assembly, resourceName).GetMockTable(); 77 | } 78 | 79 | /// 80 | private static Type[] GetTypesOfFirstDataRow(string[] values) 81 | { 82 | return values.Select(i => i.BestType()).ToArray(); 83 | } 84 | 85 | /// 86 | private static object[] ConvertStringToTypes(string[] values, Type[] types) 87 | { 88 | var result = new List(); 89 | 90 | for (int i = 0; i < values.Length; i++) 91 | { 92 | if (i < types.Length) 93 | result.Add(Convert.ChangeType(values[i], types[i])); 94 | else 95 | result.Add(values[i]); 96 | } 97 | 98 | return result.ToArray(); 99 | } 100 | } 101 | 102 | public enum CsvImportOptions 103 | { 104 | None = 0, 105 | RemoveEmptyLines = 1, 106 | TrimLines = 2, 107 | } 108 | } 109 | -------------------------------------------------------------------------------- /DbMocker/MockTableImportFixed.cs: -------------------------------------------------------------------------------- 1 | using Apps72.Dev.Data.DbMocker.Helpers; 2 | using System; 3 | using System.Collections.Generic; 4 | using System.Diagnostics; 5 | using System.IO; 6 | using System.Linq; 7 | using System.Reflection; 8 | 9 | namespace Apps72.Dev.Data.DbMocker 10 | { 11 | /// 12 | internal class MockTableImportFixed 13 | { 14 | /// 15 | /// Convert the fixed fields string to a MockResource, with a MockTable. 16 | /// 17 | /// 18 | public MockTableImportFixed(string content) 19 | { 20 | // All lines (without commented rows) 21 | this.Lines = content.Split(new char[] { '\n', '\r' }) 22 | .Where(line => String.IsNullOrWhiteSpace(line) == false) 23 | .Where(line => line.StartsWith("#") == false); 24 | 25 | // Fields positions 26 | string columnsRow = this.Lines?.ElementAtOrDefault(0); 27 | var positions = GetPositions(columnsRow).ToArray(); 28 | 29 | // Fields name 30 | var fieldsNames = SplitAtPositions(columnsRow, positions); 31 | 32 | // Data types 33 | string dataTypesRow = this.Lines?.ElementAtOrDefault(1); 34 | var dataTypes = SplitAtPositions(dataTypesRow, positions); 35 | 36 | // Combine to Fields 37 | this.Fields = positions.Select(i => new Field() 38 | { 39 | Position = i, 40 | Name = fieldsNames.ContainsKey(i) ? fieldsNames[i] : null, 41 | DataType = dataTypes.ContainsKey(i) ? dataTypes[i].KeepOnlyLetters().NameToType() : null 42 | }); 43 | 44 | // Rows 45 | var rows = new List(); 46 | for (int i = 2; i < this.Lines.Count(); i++) 47 | { 48 | var newRow = SplitAtPositions(this.Lines.ElementAt(i), positions).Select(item => item.Value); 49 | rows.Add(newRow.ToArray()); 50 | } 51 | this.Rows = GetRowsConverted(rows); 52 | } 53 | 54 | /// 55 | /// Convert the fixed fields text embedded file to a MockResource, with a MockTable. 56 | /// 57 | /// 58 | /// 59 | public MockTableImportFixed(Assembly assembly, string resourceName) 60 | : this(ReadResourceFile(assembly, resourceName)) 61 | { 62 | 63 | } 64 | 65 | /// 66 | /// Gets all lines included in the resource file. 67 | /// 68 | public IEnumerable Lines { get; } 69 | 70 | /// 71 | /// Gets all lines splitted, included in the resource file. 72 | /// 73 | public IEnumerable Rows { get; } 74 | 75 | /// 76 | /// Gets fields description 77 | /// 78 | public IEnumerable Fields { get; } 79 | 80 | /// 81 | public MockTable GetMockTable() 82 | { 83 | var columns = this.Fields.Select(i => (i.Name, i.DataType)).ToArray(); 84 | 85 | var table = new MockTable().AddColumns(columns); 86 | 87 | foreach (var row in this.Rows) 88 | { 89 | table.AddRow(row); 90 | } 91 | 92 | return table; 93 | } 94 | 95 | 96 | /// 97 | private IEnumerable GetRowsConverted(IEnumerable rows) 98 | { 99 | int fieldsCount = Fields.Count(); 100 | Type[] fieldsType = Fields.Select(i => i.DataType).ToArray(); 101 | 102 | foreach (var row in rows) 103 | { 104 | var rowConverted = new object[fieldsCount]; 105 | for (int i = 0; i < fieldsCount; i++) 106 | { 107 | try 108 | { 109 | // If not a string => String.Empty = NULL 110 | if (fieldsType[i] != typeof(string) && String.IsNullOrEmpty(row[i])) 111 | { 112 | row[i] = "NULL"; 113 | } 114 | 115 | if (fieldsType[i] != null && String.Compare(row[i], "NULL", ignoreCase: true) != 0) 116 | { 117 | // Convert 118 | var converter = System.ComponentModel.TypeDescriptor.GetConverter(fieldsType[i]); 119 | rowConverted[i] = Convert.ChangeType(converter.ConvertFromInvariantString(row[i]), fieldsType[i]); 120 | 121 | // Guillemets 122 | if (fieldsType[i] == typeof(string) && row[i].Length >= 2 && row[i][0] == '"' && row[i][row[i].Length - 1] == '"') 123 | { 124 | rowConverted[i] = row[i].Substring(1, row[i].Length - 2); 125 | } 126 | } 127 | } 128 | catch (Exception) 129 | { 130 | throw new InvalidCastException($"Invalid conversion of \"{row[i]}\" to \"{fieldsType[i].Name}\", for column \"{Fields.ElementAt(i).Name}\"."); 131 | } 132 | } 133 | yield return rowConverted; 134 | } 135 | } 136 | 137 | /// 138 | /// Split specified text line to data using fixed positions. 139 | /// 140 | /// 141 | /// 142 | /// 143 | private Dictionary SplitAtPositions(string line, int[] positions) 144 | { 145 | var result = new Dictionary(); 146 | int numberOfPosition = positions.Length; 147 | 148 | if (!String.IsNullOrEmpty(line)) 149 | { 150 | for (int i = 0; i < numberOfPosition; i++) 151 | { 152 | int indexFrom = positions[i]; 153 | int? indexTo = (i + 1) < numberOfPosition 154 | ? positions[i + 1] 155 | : (int?)null; 156 | 157 | if (indexFrom < line.Length) 158 | { 159 | string part = indexTo != null && indexTo < line.Length 160 | ? line.Substring(indexFrom, indexTo.Value - indexFrom) 161 | : line.Substring(indexFrom); 162 | 163 | part = part.Trim(); 164 | 165 | result.Add(indexFrom, part); 166 | } 167 | else 168 | { 169 | 170 | } 171 | } 172 | } 173 | 174 | return result; 175 | } 176 | 177 | /// 178 | /// Gets all index positions of words 179 | /// "ABC 123" => [0, 4] 180 | /// 181 | /// 182 | /// 183 | private IEnumerable GetPositions(string line) 184 | { 185 | var positions = new List(); 186 | bool findNext = true; 187 | 188 | for (int i = 0; i < line.Length; i++) 189 | { 190 | char item = line[i]; 191 | 192 | if (item == ' ' || item == '\t') 193 | findNext = true; 194 | 195 | if (findNext && item != ' ' && item != '\t') 196 | { 197 | positions.Add(i); 198 | findNext = false; 199 | } 200 | } 201 | 202 | return positions; 203 | } 204 | 205 | /// 206 | /// Read the resource text file. 207 | /// 208 | /// 209 | /// 210 | /// 211 | private static string ReadResourceFile(Assembly assembly, string resourceName) 212 | { 213 | using (Stream stream = assembly.GetManifestResourceStream(resourceName)) 214 | using (StreamReader reader = new StreamReader(stream)) 215 | { 216 | return reader.ReadToEnd(); 217 | } 218 | } 219 | 220 | /// 221 | [DebuggerDisplay("[{Position}] {Name} ({DataType})")] 222 | public class Field 223 | { 224 | /// 225 | public string Name { get; internal set; } 226 | /// 227 | public int Position { get; internal set; } 228 | /// 229 | public Type DataType { get; internal set; } 230 | } 231 | } 232 | } 233 | -------------------------------------------------------------------------------- /DbMocker/MockTableStatic.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | 3 | namespace Apps72.Dev.Data.DbMocker 4 | { 5 | /// 6 | public partial class MockTable 7 | { 8 | /// 9 | public static MockTable Empty() 10 | { 11 | return new MockTable(); 12 | } 13 | 14 | /// 15 | public static MockTable WithColumns(params string[] columns) 16 | { 17 | return new MockTable() 18 | { 19 | Columns = DbMocker.Columns.WithNames(columns) 20 | }; 21 | } 22 | 23 | public static MockTable WithColumns(params (string Name, Type Type)[] columns) 24 | { 25 | return new MockTable() 26 | { 27 | Columns = DbMocker.Columns.WithNames(columns) 28 | }; 29 | } 30 | 31 | /// 32 | public static MockTable SingleCell(string columnName, object value) 33 | { 34 | return new MockTable() 35 | { 36 | Columns = DbMocker.Columns.WithNames(columnName), 37 | Rows = new[,] { { value } }, 38 | }; 39 | } 40 | 41 | /// 42 | public static MockTable SingleCell(object value) 43 | { 44 | return SingleCell(String.Empty, value); 45 | } 46 | } 47 | } 48 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | The MIT License (MIT) 2 | 3 | Copyright (c) dvoituron and Contributors 4 | 5 | All rights reserved. 6 | 7 | Permission is hereby granted, free of charge, to any person obtaining a copy 8 | of this software and associated documentation files (the "Software"), to deal 9 | in the Software without restriction, including without limitation the rights 10 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 11 | copies of the Software, and to permit persons to whom the Software is 12 | furnished to do so, subject to the following conditions: 13 | 14 | The above copyright notice and this permission notice shall be included in all 15 | copies or substantial portions of the Software. 16 | 17 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 18 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 19 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 20 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 21 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 22 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 23 | SOFTWARE. 24 | -------------------------------------------------------------------------------- /ReadMe.md: -------------------------------------------------------------------------------- 1 | # DbMocker - Simple Database Mocker for UnitTests 2 | 3 | ## Introduction 4 | 5 | This .NET library simplifies data mocking for UnitTests, to avoid a connection to a relational database. 6 | DbMocker use the standard Microsoft .NET DbConnection object. So, you can mock any toolkit, 7 | including EntityFramework, Dapper or ADO.NET; And for all database servers (SQL Server, Oracle, SQLite). 8 | 9 | First, add the [DbMocker NuGet packages](https://www.nuget.org/packages/DbMocker). 10 | Next, instanciate a `MockDbConnection` and mock you SQL requests using a condition and return a DataTable. 11 | 12 | Please, contact me if you want other features or to solve bugs. 13 | 14 | ```CSharp 15 | // Sample method from your DataService 16 | public int GetNumberOfEmployees(DbConnection connection) 17 | { 18 | using (var cmd = connection.CreateCommand()) 19 | { 20 | cmd.CommandText = "SELECT COUNT(*) FROM Employees"; 21 | return Convert.ToInt32(cmd.ExecuteScalar()); 22 | } 23 | } 24 | 25 | /* Create a text file "123-EMPLOYEES.txt" with this content 26 | And set the build property to "Embedded resource". 27 | Id Name Age 28 | (int) (string) (int?) 29 | 30 | 10 Scott 21 31 | 20 Bill NULL 32 | */ 33 | 34 | [TestMethod] 35 | public void UnitTest0() 36 | { 37 | var conn = new MockDbConnection(); 38 | 39 | // The text file "123-EMPLOYEES.txt" is embedded in this project. 40 | // See the Samples folder. 41 | // - 123 is an identifier (as you want) 42 | // - EMPLOYEES is the CommandText Tag 43 | // See https://docs.microsoft.com/en-us/ef/core/querying/tags 44 | conn.Mocks.LoadTagsFromResources("123-EMPLOYEES"); 45 | 46 | // Call your "classic" methods to tests 47 | var data = GetEmployees(conn); 48 | 49 | // DbMocker read the embedded file 50 | // and associated the content to the tag 51 | Assert.AreEqual("Scott", data[0][1]); 52 | Assert.AreEqual("Bill", data[1][1]); 53 | } 54 | 55 | [TestMethod] 56 | public void UnitTest1() 57 | { 58 | var conn = new MockDbConnection(); 59 | 60 | // When a specific SQL command is detected, 61 | // Don't execute the query to your database engine (SQL Server, Oracle, SQLite, ...), 62 | // But returns this _Table_. 63 | conn.Mocks 64 | .When(cmd => cmd.CommandText.StartsWith("SELECT") && 65 | cmd.Parameters.Count() == 0) 66 | .ReturnsTable(MockTable.WithColumns("Count") 67 | .AddRow(14)); 68 | 69 | // Call your "classic" methods to tests 70 | int count = GetNumberOfEmployees(conn); 71 | 72 | Assert.AreEqual(14, count); 73 | } 74 | ``` 75 | 76 | See [https://apps72.com](https://apps72.com) for more information. 77 | 78 | 79 | 80 | 81 | 82 | 83 | 84 | ## Conditions 85 | 86 | Use the `When` method to describe the condition to be detected. 87 | This condition is based on a Lambda expression containing a CommandText or Parameters check. 88 | 89 | ```CSharp 90 | conn.Mocks 91 | .When(cmd => cmd.CommandText.StartsWith("SELECT") && 92 | cmd.Parameters.Count() == 0) 93 | .ReturnsTable(...); 94 | ``` 95 | 96 | Use the `WhenTag` method to detect query containing a row starting with `-- MyTag`. 97 | This is compatible with EFCore 2.2, containing a new extension method `WithTag` to identity a request. 98 | 99 | ```CSharp 100 | conn.Mocks 101 | .WhenTag("MyTag") 102 | .ReturnsTable(...); 103 | ``` 104 | 105 | Use `WhenAny` to detect all SQL queries. In this case, all queries to the database will return the data specified by WhenAny. 106 | 107 | ```CSharp 108 | conn.Mocks 109 | .WhenAny() 110 | .ReturnsTable(...); 111 | ``` 112 | 113 | ## ReturnsTable 114 | 115 | When the previous condition occured, a mocked table will be return: 116 | 117 | Creating an new instance of **MockTable**. 118 | 119 | ```CSharp 120 | conn.Mocks 121 | .WhenAny() 122 | .ReturnsTable(new MockTable().AddColumns("ID", "Name") 123 | .AddRow(1, "Scott") 124 | .AddRow(2, "Bill")); 125 | ``` 126 | 127 | Using a **MockTable.Empty()** table... to complete. 128 | 129 | ```CSharp 130 | conn.Mocks 131 | .WhenAny() 132 | .ReturnsTable(MockTable.Empty() 133 | .AddColumns("ID", "Name") 134 | .AddRow(1, "Scott") 135 | .AddRow(2, "Bill")); 136 | ``` 137 | 138 | Using a **MockTable.WithColumns()** table... to complete. 139 | 140 | ```CSharp 141 | conn.Mocks 142 | .WhenAny() 143 | .ReturnsTable(MockTable.WithColumns("ID", "Name") 144 | .AddRow(1, "Scott") 145 | .AddRow(2, "Bill")); 146 | ``` 147 | 148 | Using a **MockTable.WithColumns()** typed columns. In this case, columns are defined using a tuple (ColumnName, ColumnType). 149 | 150 | ```CSharp 151 | conn.Mocks 152 | .WhenAny() 153 | .ReturnsTable(MockTable.WithColumns(("ID", typeof(int?)), 154 | ("Name", typeof(string))) 155 | .AddRow(null, "Scott") 156 | .AddRow(2, "Bill")); 157 | ``` 158 | 159 | Returning a **MockTable.SingleCell()** table... to complete. 160 | 161 | ```CSharp 162 | conn.Mocks 163 | .WhenAny() 164 | .ReturnsTable(MockTable.SingleCell("Count", 14)); 165 | ``` 166 | 167 | Using an expression to customize the return. 168 | 169 | ```CSharp 170 | conn.Mocks 171 | .WhenAny() 172 | .ReturnsTable(cmd => cmd.Parameters.Count() > 0 ? 14 : 99); 173 | ``` 174 | 175 | using a **CSV string** with all data. 176 | The first row contains the column names. 177 | The first data row defines types for each columns (like in a Excel importation). 178 | 179 | ```CSharp 180 | string csv = @" Id Name Birthdate 181 | 1 Scott 1980-02-03 182 | 2 Bill 1972-01-12 183 | 3 Anders 1965-03-14 "; 184 | 185 | conn.Mocks 186 | .WhenAny() 187 | .ReturnsTable(MockTable.FromCsv(csv)); 188 | ``` 189 | 190 | ## ReturnsRow 191 | 192 | When a condition occured, a single data row will be return. 193 | The specified typed object will generate a MockTable where property names will be the column names 194 | and proerty values will be the first row data. 195 | 196 | ```CSharp 197 | conn.Mocks 198 | .WhenAny() 199 | .ReturnsRow(new { Id = 1, Name = "Denis" }); 200 | ``` 201 | 202 | 203 | Using an expression to customize the return. 204 | 205 | ```CSharp 206 | conn.Mocks 207 | .WhenAny() 208 | .ReturnsRow(cmd => new { Id = 1, Name = "Denis" }); 209 | ``` 210 | 211 | ## ReturnsScalar 212 | 213 | When a condition occured, a scalar value will be return: 214 | 215 | ```CSharp 216 | conn.Mocks 217 | .WhenAny() 218 | .ReturnsScalar(14); 219 | ``` 220 | 221 | ```CSharp 222 | conn.Mocks 223 | .WhenAny() 224 | .ReturnsScalar(cmd => DateTime.Today.Year > 2000 ? 14 : 0); 225 | ``` 226 | 227 | ## Check the SQL Server query syntax 228 | 229 | Call the method `Mocks.HasValidSqlServerCommandText()` 230 | to check if your string **CommandText** respect the SQL Server syntax... 231 | without connection to SQL Server (but using the [Microsoft.SqlServer.SqlParser](https://www.nuget.org/packages/Microsoft.SqlServer.SqlParser) package). 232 | 233 | ```CSharp 234 | conn.Mocks 235 | .HasValidSqlServerCommandText() 236 | .WhenAny() 237 | .ReturnsScalar(14); 238 | ``` 239 | 240 | So the `CommandText="SELECT ** FROM EMP"` (double *) 241 | will raised a **MockException** with the message "Incorrect syntax near '*'". 242 | 243 | You can also define a default value using the `MockDbConnection.HasValidSqlServerCommandText` property. 244 | 245 | ```CSharp 246 | var conn = new MockDbConnection() 247 | { 248 | HasValidSqlServerCommandText = true 249 | }; 250 | ``` 251 | 252 | ## Releases 253 | 254 | ## Version 1.26 255 | - #40 Add the Callback support to MockReturns with unit test. 256 | Thanks [Tridy](https://github.com/Tridy). 257 | 258 | ## Version 1.25 259 | - #36 Accept white list of properties, with `MockTable.FromType` method. 260 | Thanks [zewa666](https://github.com/zewa666). 261 | 262 | ## Version 1.24 263 | - #35 `MockDbDataReader.GetBytes` does fill the `buffer` param. 264 | Thanks [Stepami](https://github.com/Stepami). 265 | 266 | ## Version 1.23 267 | - Dependencies updated. 268 | - #32 Update `MockDbDataReader.IsClosed` 269 | Thanks [kiainlogicdk](https://github.com/kiainlogicdk) for the discussion. 270 | 271 | ## Version 1.22 272 | - #31 Implement the `DbDataReader.GetSchemaTable()` method. 273 | Thanks [javnov](https://github.com/javnov). 274 | 275 | ## Version 1.21 276 | - #29 Fix `Dispose` method to change the ConnectionState to Closed. 277 | Thanks [OlegKrymskyi](https://github.com/OlegKrymskyi). 278 | 279 | ## Version 1.20 280 | - #27 Fix `ExecuteScalar` method to respect the Microsoft documentation. 281 | _"If the first column of the first row in the result set is not found, a null reference is returned. 282 | If the value in the database is null, the query returns DBNull.Value."_ 283 | Thanks [Andreas](https://github.com/htw8441). 284 | 285 | ## Version 1.19 286 | - Use a direct reference to SqlParser.dll. 287 | Thanks [yyalkovich](https://github.com/yyalkovich). 288 | 289 | ## Version 1.18 290 | - Add methods `ThrowsException()` to throw an exception when a condition has occured. 291 | Thanks [wessonben](https://github.com/wessonben). 292 | 293 | ## Version 1.17 294 | - Fix consistent NewLine detection (\n, \r or both), used by `WhenTag` method. 295 | Thanks [martinsmith1968](https://github.com/martinsmith1968). 296 | 297 | ## Version 1.16 298 | - Add `MockTable.FromType` method to fill a mock table using existing .NET objects. 299 | Thanks [martinsmith1968](https://github.com/martinsmith1968). 300 | 301 | ## Version 1.15 302 | - Fix `MockDbDataReader.IsDBNull` when the value is null. 303 | 304 | ## Version 1.14 305 | - Add 'Guid' type in `MockTable.FromFixed` and resource sample files. 306 | - Add a custom message when a sample conversion fails. Ex: `Invalid conversion of "2020-01-32" to "DateTime", for column "Col1"`. 307 | 308 | ## Version 1.13 309 | - Set output value for DbParameter, using `MockResturns.SetParameterValue` method. 310 | Thanks [unby](https://github.com/unby). 311 | - Fix `MockDbDataReader.HasRows` to return true when at least a row is existing. 312 | Thanks [htw8441](https://github.com/htw8441). 313 | 314 | ### Version 1.12 315 | - Fix the fixed format (resource files) to convert values using Invariant Culture. 316 | 317 | ### Version 1.10 and 11 318 | - Minor fixes to deploy nuget. 319 | 320 | ### Version 1.9 321 | - Add `MockResourceOptions.TagSeparator` (default is '-') to allow to include multiple MockTable resource samples. 322 | "01-MyTag.txt" and "02-MyTag.txt" are two resource using the same SQL tag (MyTag). 323 | 324 | ### Version 1.8 325 | - Add `Mocks.LoadTagsFromResources` to include MockTable samples described in Embedded resource text files. 326 | 327 | ### Version 1.7 328 | - Add `ReturnsDataset` methods to simulate multiple tables (Thanks [stop-cran](https://github.com/stop-cran)). 329 | - Update the reference to the Nuget **Microsoft.SqlServer.Management.SqlParser** to validate syntaxes of SQL queries. 330 | 331 | ### Version 1.6 332 | - Add detailed SQL Query in MockException properties (#6). 333 | - Add a new WhenTag method (#7). 334 | - Add a method to validate the syntax of SQL queries without connection to SQL Server (only for SQL Server syntax) (#8). 335 | 336 | ### Version 1.5 337 | - Add a `MockColumn` class to manage the column type. See example using "typed columns" above. 338 | - Breaking change: to allow typed MockColumn, the property `MockTable.Columns` is now of type MockColumn[] (previously string[]). 339 | 340 | ### Version 1.4 341 | - Add `MockTable.FromCsv(string)` method. 342 | 343 | ### Version 1.3 344 | - Add `ReturnsRow(T)` and `ReturnsRow(Func)` methods. 345 | -------------------------------------------------------------------------------- /spelling.dic: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Apps72/DbMocker/bb1bdec2551af95d5a82dee54bf00ff53cb1dbdc/spelling.dic --------------------------------------------------------------------------------