├── .dockerignore ├── .gitignore ├── Dockerfile ├── Readme.md ├── TestingWithContainers.WebApp ├── Program.cs ├── Properties │ └── launchSettings.json ├── TestingWithContainers.WebApp.csproj ├── appsettings.Development.json └── appsettings.json ├── TestingWithContainers.sln ├── TestingWithContainers ├── CustomContainerTest.cs ├── DatabaseContainerPerCollection.cs ├── DatabaseContainerPerTest.cs ├── DatabaseContainerPerTestClass.cs ├── DatabaseFixture.cs ├── GlobalUsings.cs ├── HttpTest.cs ├── Person.cs ├── TestingWithContainers.csproj └── WebAppWithDatabase.cs └── global.json /.dockerignore: -------------------------------------------------------------------------------- 1 | **/.dockerignore 2 | **/.env 3 | **/.git 4 | **/.gitignore 5 | **/.project 6 | **/.settings 7 | **/.toolstarget 8 | **/.vs 9 | **/.vscode 10 | **/.idea 11 | **/*.*proj.user 12 | **/*.dbmdl 13 | **/*.jfm 14 | **/azds.yaml 15 | **/bin 16 | **/charts 17 | **/docker-compose* 18 | **/Dockerfile* 19 | **/node_modules 20 | **/npm-debug.log 21 | **/obj 22 | **/secrets.dev.yaml 23 | **/values.dev.yaml 24 | LICENSE 25 | README.md -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | ## Ignore Visual Studio temporary files, build results, and 2 | ## files generated by popular Visual Studio add-ons. 3 | ## 4 | ## Get latest from `dotnet new gitignore` 5 | 6 | # dotenv files 7 | .env 8 | 9 | # User-specific files 10 | *.rsuser 11 | *.suo 12 | *.user 13 | *.userosscache 14 | *.sln.docstates 15 | 16 | # User-specific files (MonoDevelop/Xamarin Studio) 17 | *.userprefs 18 | 19 | # Mono auto generated files 20 | mono_crash.* 21 | 22 | # Build results 23 | [Dd]ebug/ 24 | [Dd]ebugPublic/ 25 | [Rr]elease/ 26 | [Rr]eleases/ 27 | x64/ 28 | x86/ 29 | [Ww][Ii][Nn]32/ 30 | [Aa][Rr][Mm]/ 31 | [Aa][Rr][Mm]64/ 32 | bld/ 33 | [Bb]in/ 34 | [Oo]bj/ 35 | [Ll]og/ 36 | [Ll]ogs/ 37 | 38 | # Visual Studio 2015/2017 cache/options directory 39 | .vs/ 40 | # Uncomment if you have tasks that create the project's static files in wwwroot 41 | #wwwroot/ 42 | 43 | # Visual Studio 2017 auto generated files 44 | Generated\ Files/ 45 | 46 | # MSTest test Results 47 | [Tt]est[Rr]esult*/ 48 | [Bb]uild[Ll]og.* 49 | 50 | # NUnit 51 | *.VisualState.xml 52 | TestResult.xml 53 | nunit-*.xml 54 | 55 | # Build Results of an ATL Project 56 | [Dd]ebugPS/ 57 | [Rr]eleasePS/ 58 | dlldata.c 59 | 60 | # Benchmark Results 61 | BenchmarkDotNet.Artifacts/ 62 | 63 | # .NET 64 | project.lock.json 65 | project.fragment.lock.json 66 | artifacts/ 67 | 68 | # Tye 69 | .tye/ 70 | 71 | # ASP.NET Scaffolding 72 | ScaffoldingReadMe.txt 73 | 74 | # StyleCop 75 | StyleCopReport.xml 76 | 77 | # Files built by Visual Studio 78 | *_i.c 79 | *_p.c 80 | *_h.h 81 | *.ilk 82 | *.meta 83 | *.obj 84 | *.iobj 85 | *.pch 86 | *.pdb 87 | *.ipdb 88 | *.pgc 89 | *.pgd 90 | *.rsp 91 | *.sbr 92 | *.tlb 93 | *.tli 94 | *.tlh 95 | *.tmp 96 | *.tmp_proj 97 | *_wpftmp.csproj 98 | *.log 99 | *.tlog 100 | *.vspscc 101 | *.vssscc 102 | .builds 103 | *.pidb 104 | *.svclog 105 | *.scc 106 | 107 | # Chutzpah Test files 108 | _Chutzpah* 109 | 110 | # Visual C++ cache files 111 | ipch/ 112 | *.aps 113 | *.ncb 114 | *.opendb 115 | *.opensdf 116 | *.sdf 117 | *.cachefile 118 | *.VC.db 119 | *.VC.VC.opendb 120 | 121 | # Visual Studio profiler 122 | *.psess 123 | *.vsp 124 | *.vspx 125 | *.sap 126 | 127 | # Visual Studio Trace Files 128 | *.e2e 129 | 130 | # TFS 2012 Local Workspace 131 | $tf/ 132 | 133 | # Guidance Automation Toolkit 134 | *.gpState 135 | 136 | # ReSharper is a .NET coding add-in 137 | _ReSharper*/ 138 | *.[Rr]e[Ss]harper 139 | *.DotSettings.user 140 | 141 | # TeamCity is a build add-in 142 | _TeamCity* 143 | 144 | # DotCover is a Code Coverage Tool 145 | *.dotCover 146 | 147 | # AxoCover is a Code Coverage Tool 148 | .axoCover/* 149 | !.axoCover/settings.json 150 | 151 | # Coverlet is a free, cross platform Code Coverage Tool 152 | coverage*.json 153 | coverage*.xml 154 | coverage*.info 155 | 156 | # Visual Studio code coverage results 157 | *.coverage 158 | *.coveragexml 159 | 160 | # NCrunch 161 | _NCrunch_* 162 | .*crunch*.local.xml 163 | nCrunchTemp_* 164 | 165 | # MightyMoose 166 | *.mm.* 167 | AutoTest.Net/ 168 | 169 | # Web workbench (sass) 170 | .sass-cache/ 171 | 172 | # Installshield output folder 173 | [Ee]xpress/ 174 | 175 | # DocProject is a documentation generator add-in 176 | DocProject/buildhelp/ 177 | DocProject/Help/*.HxT 178 | DocProject/Help/*.HxC 179 | DocProject/Help/*.hhc 180 | DocProject/Help/*.hhk 181 | DocProject/Help/*.hhp 182 | DocProject/Help/Html2 183 | DocProject/Help/html 184 | 185 | # Click-Once directory 186 | publish/ 187 | 188 | # Publish Web Output 189 | *.[Pp]ublish.xml 190 | *.azurePubxml 191 | # Note: Comment the next line if you want to checkin your web deploy settings, 192 | # but database connection strings (with potential passwords) will be unencrypted 193 | *.pubxml 194 | *.publishproj 195 | 196 | # Microsoft Azure Web App publish settings. Comment the next line if you want to 197 | # checkin your Azure Web App publish settings, but sensitive information contained 198 | # in these scripts will be unencrypted 199 | PublishScripts/ 200 | 201 | # NuGet Packages 202 | *.nupkg 203 | # NuGet Symbol Packages 204 | *.snupkg 205 | # The packages folder can be ignored because of Package Restore 206 | **/[Pp]ackages/* 207 | # except build/, which is used as an MSBuild target. 208 | !**/[Pp]ackages/build/ 209 | # Uncomment if necessary however generally it will be regenerated when needed 210 | #!**/[Pp]ackages/repositories.config 211 | # NuGet v3's project.json files produces more ignorable files 212 | *.nuget.props 213 | *.nuget.targets 214 | 215 | # Microsoft Azure Build Output 216 | csx/ 217 | *.build.csdef 218 | 219 | # Microsoft Azure Emulator 220 | ecf/ 221 | rcf/ 222 | 223 | # Windows Store app package directories and files 224 | AppPackages/ 225 | BundleArtifacts/ 226 | Package.StoreAssociation.xml 227 | _pkginfo.txt 228 | *.appx 229 | *.appxbundle 230 | *.appxupload 231 | 232 | # Visual Studio cache files 233 | # files ending in .cache can be ignored 234 | *.[Cc]ache 235 | # but keep track of directories ending in .cache 236 | !?*.[Cc]ache/ 237 | 238 | # Others 239 | ClientBin/ 240 | ~$* 241 | *~ 242 | *.dbmdl 243 | *.dbproj.schemaview 244 | *.jfm 245 | *.pfx 246 | *.publishsettings 247 | orleans.codegen.cs 248 | 249 | # Including strong name files can present a security risk 250 | # (https://github.com/github/gitignore/pull/2483#issue-259490424) 251 | #*.snk 252 | 253 | # Since there are multiple workflows, uncomment next line to ignore bower_components 254 | # (https://github.com/github/gitignore/pull/1529#issuecomment-104372622) 255 | #bower_components/ 256 | 257 | # RIA/Silverlight projects 258 | Generated_Code/ 259 | 260 | # Backup & report files from converting an old project file 261 | # to a newer Visual Studio version. Backup files are not needed, 262 | # because we have git ;-) 263 | _UpgradeReport_Files/ 264 | Backup*/ 265 | UpgradeLog*.XML 266 | UpgradeLog*.htm 267 | ServiceFabricBackup/ 268 | *.rptproj.bak 269 | 270 | # SQL Server files 271 | *.mdf 272 | *.ldf 273 | *.ndf 274 | 275 | # Business Intelligence projects 276 | *.rdl.data 277 | *.bim.layout 278 | *.bim_*.settings 279 | *.rptproj.rsuser 280 | *- [Bb]ackup.rdl 281 | *- [Bb]ackup ([0-9]).rdl 282 | *- [Bb]ackup ([0-9][0-9]).rdl 283 | 284 | # Microsoft Fakes 285 | FakesAssemblies/ 286 | 287 | # GhostDoc plugin setting file 288 | *.GhostDoc.xml 289 | 290 | # Node.js Tools for Visual Studio 291 | .ntvs_analysis.dat 292 | node_modules/ 293 | 294 | # Visual Studio 6 build log 295 | *.plg 296 | 297 | # Visual Studio 6 workspace options file 298 | *.opt 299 | 300 | # Visual Studio 6 auto-generated workspace file (contains which files were open etc.) 301 | *.vbw 302 | 303 | # Visual Studio 6 auto-generated project file (contains which files were open etc.) 304 | *.vbp 305 | 306 | # Visual Studio 6 workspace and project file (working project files containing files to include in project) 307 | *.dsw 308 | *.dsp 309 | 310 | # Visual Studio 6 technical files 311 | *.ncb 312 | *.aps 313 | 314 | # Visual Studio LightSwitch build output 315 | **/*.HTMLClient/GeneratedArtifacts 316 | **/*.DesktopClient/GeneratedArtifacts 317 | **/*.DesktopClient/ModelManifest.xml 318 | **/*.Server/GeneratedArtifacts 319 | **/*.Server/ModelManifest.xml 320 | _Pvt_Extensions 321 | 322 | # Paket dependency manager 323 | .paket/paket.exe 324 | paket-files/ 325 | 326 | # FAKE - F# Make 327 | .fake/ 328 | 329 | # CodeRush personal settings 330 | .cr/personal 331 | 332 | # Python Tools for Visual Studio (PTVS) 333 | __pycache__/ 334 | *.pyc 335 | 336 | # Cake - Uncomment if you are using it 337 | # tools/** 338 | # !tools/packages.config 339 | 340 | # Tabs Studio 341 | *.tss 342 | 343 | # Telerik's JustMock configuration file 344 | *.jmconfig 345 | 346 | # BizTalk build output 347 | *.btp.cs 348 | *.btm.cs 349 | *.odx.cs 350 | *.xsd.cs 351 | 352 | # OpenCover UI analysis results 353 | OpenCover/ 354 | 355 | # Azure Stream Analytics local run output 356 | ASALocalRun/ 357 | 358 | # MSBuild Binary and Structured Log 359 | *.binlog 360 | 361 | # NVidia Nsight GPU debugger configuration file 362 | *.nvuser 363 | 364 | # MFractors (Xamarin productivity tool) working folder 365 | .mfractor/ 366 | 367 | # Local History for Visual Studio 368 | .localhistory/ 369 | 370 | # Visual Studio History (VSHistory) files 371 | .vshistory/ 372 | 373 | # BeatPulse healthcheck temp database 374 | healthchecksdb 375 | 376 | # Backup folder for Package Reference Convert tool in Visual Studio 2017 377 | MigrationBackup/ 378 | 379 | # Ionide (cross platform F# VS Code tools) working folder 380 | .ionide/ 381 | 382 | # Fody - auto-generated XML schema 383 | FodyWeavers.xsd 384 | 385 | # VS Code files for those working on multiple tools 386 | .vscode/* 387 | !.vscode/settings.json 388 | !.vscode/tasks.json 389 | !.vscode/launch.json 390 | !.vscode/extensions.json 391 | *.code-workspace 392 | 393 | # Local History for Visual Studio Code 394 | .history/ 395 | 396 | # Windows Installer files from build outputs 397 | *.cab 398 | *.msi 399 | *.msix 400 | *.msm 401 | *.msp 402 | 403 | # JetBrains Rider 404 | *.sln.iml 405 | .idea 406 | 407 | ## 408 | ## Visual studio for Mac 409 | ## 410 | 411 | 412 | # globs 413 | Makefile.in 414 | *.userprefs 415 | *.usertasks 416 | config.make 417 | config.status 418 | aclocal.m4 419 | install-sh 420 | autom4te.cache/ 421 | *.tar.gz 422 | tarballs/ 423 | test-results/ 424 | 425 | # Mac bundle stuff 426 | *.dmg 427 | *.app 428 | 429 | # content below from: https://github.com/github/gitignore/blob/master/Global/macOS.gitignore 430 | # General 431 | .DS_Store 432 | .AppleDouble 433 | .LSOverride 434 | 435 | # Icon must end with two \r 436 | Icon 437 | 438 | 439 | # Thumbnails 440 | ._* 441 | 442 | # Files that might appear in the root of a volume 443 | .DocumentRevisions-V100 444 | .fseventsd 445 | .Spotlight-V100 446 | .TemporaryItems 447 | .Trashes 448 | .VolumeIcon.icns 449 | .com.apple.timemachine.donotpresent 450 | 451 | # Directories potentially created on remote AFP share 452 | .AppleDB 453 | .AppleDesktop 454 | Network Trash Folder 455 | Temporary Items 456 | .apdisk 457 | 458 | # content below from: https://github.com/github/gitignore/blob/master/Global/Windows.gitignore 459 | # Windows thumbnail cache files 460 | Thumbs.db 461 | ehthumbs.db 462 | ehthumbs_vista.db 463 | 464 | # Dump file 465 | *.stackdump 466 | 467 | # Folder config file 468 | [Dd]esktop.ini 469 | 470 | # Recycle Bin used on file shares 471 | $RECYCLE.BIN/ 472 | 473 | # Windows Installer files 474 | *.cab 475 | *.msi 476 | *.msix 477 | *.msm 478 | *.msp 479 | 480 | # Windows shortcuts 481 | *.lnk 482 | 483 | # Vim temporary swap files 484 | *.swp 485 | -------------------------------------------------------------------------------- /Dockerfile: -------------------------------------------------------------------------------- 1 | FROM mcr.microsoft.com/dotnet/aspnet:8.0 AS base 2 | WORKDIR /app 3 | EXPOSE 80 4 | EXPOSE 443 5 | 6 | FROM mcr.microsoft.com/dotnet/sdk:8.0 AS build 7 | ARG BUILD_CONFIGURATION=Release 8 | WORKDIR /src 9 | COPY ["TestingWithContainers.WebApp/TestingWithContainers.WebApp.csproj", "TestingWithContainers.WebApp/"] 10 | RUN dotnet restore "TestingWithContainers.WebApp/TestingWithContainers.WebApp.csproj" 11 | COPY . . 12 | WORKDIR "/src/TestingWithContainers.WebApp" 13 | RUN dotnet build "TestingWithContainers.WebApp.csproj" -c $BUILD_CONFIGURATION -o /app/build 14 | 15 | FROM build AS publish 16 | ARG BUILD_CONFIGURATION=Release 17 | RUN dotnet publish "TestingWithContainers.WebApp.csproj" -c $BUILD_CONFIGURATION -o /app/publish /p:UseAppHost=false 18 | 19 | FROM base AS final 20 | WORKDIR /app 21 | COPY --from=publish /app/publish . 22 | ENTRYPOINT ["dotnet", "TestingWithContainers.WebApp.dll"] 23 | -------------------------------------------------------------------------------- /Readme.md: -------------------------------------------------------------------------------- 1 | # Using TestContainers for Integration Tests 2 | 3 | This repository contains strategies for integration testing with [TestContainers](https://dotnet.testcontainers.org/) and XUnit. Specifically, these tests show how to use XUnit's facilities to provide dependencies on several levels: 4 | 5 | - Dependency per test 6 | - Dependency per test class 7 | - Dependency per test collection 8 | 9 | These three strategies provide varying levels of execution speed and test isolation. 10 | 11 | The strategy you choose will be based on your scenarios and preferred outcome. 12 | 13 | As a general rule, it's best to start with **dependency per test**, as it provides the most isolation between tests, but it can be time-intensive as your test suite grows. 14 | 15 | The other strategies can be powerful in speeding up your test runs, but require thinking about initialization and clean-up strategies as state can "leak" between tests. 16 | 17 | ## Other Scenarios You Might Be Interested In 18 | 19 | I've also included two tests that might be of interest to folks writing integration tests. 20 | Pulling an image from the registry ([HttpTest](./TestingWithContainers/HttpTest.cs)), and Building a custom image and running it as a container ([CustomContainerTest](./TestingWithContainers/CustomContainerTest.cs)). 21 | 22 | In general, TestContainers are infinitely configurable for your testing needs, but the library requires some work on your part. 23 | 24 | ## Getting Started 25 | 26 | You'll need the following to run these tests. 27 | 28 | - .NET 8 SDK 29 | - JetBrains Rider (optional) 30 | 31 | Running the tests in the JetBrains Rider test runner will show how tests are isolated, as the **Container Id** is printed to the test runner output window. Also note the time it takes to execute each collection of tests. 32 | 33 | On my machine, the tests take about this much time: 34 | 35 | - Dependency per test: 3 tests @ 13 seconds. 36 | - Dependency per test class: 3 tests @ 9 seconds 37 | - Dependency per test collection: 6 tests @ 4 seconds 38 | 39 | Each strategy is running identical tests. -------------------------------------------------------------------------------- /TestingWithContainers.WebApp/Program.cs: -------------------------------------------------------------------------------- 1 | using System.Data.Common; 2 | using Dapper; 3 | using Npgsql; 4 | 5 | var builder = WebApplication.CreateBuilder(args); 6 | 7 | builder.Services.AddScoped(static sp => { 8 | var config = sp.GetRequiredService(); 9 | var connectionString = config.GetConnectionString("database"); 10 | var connection = new NpgsqlConnection(connectionString); 11 | connection.Open(); 12 | return connection; 13 | }); 14 | 15 | var app = builder.Build(); 16 | 17 | app.MapGet("/", () => "Hello World!"); 18 | app.MapGet("/database", async (DbConnection db, string? make) => 19 | { 20 | if (make is null) 21 | return Results.NotFound(); 22 | 23 | var car = await db.QueryFirstAsync( 24 | "select * from Cars where make = @make", 25 | new { make } 26 | ); 27 | 28 | return car is not null 29 | ? Results.Ok(car) 30 | : Results.NotFound(); 31 | }); 32 | 33 | app.Run(); 34 | 35 | 36 | public class Car 37 | { 38 | public int Id { get; set; } 39 | public string Make { get; set; } 40 | public string Model { get; set; } 41 | public int Year { get; set; } 42 | } -------------------------------------------------------------------------------- /TestingWithContainers.WebApp/Properties/launchSettings.json: -------------------------------------------------------------------------------- 1 | { 2 | "$schema": "http://json.schemastore.org/launchsettings.json", 3 | "iisSettings": { 4 | "windowsAuthentication": false, 5 | "anonymousAuthentication": true, 6 | "iisExpress": { 7 | "applicationUrl": "http://localhost:7948", 8 | "sslPort": 44389 9 | } 10 | }, 11 | "profiles": { 12 | "http": { 13 | "commandName": "Project", 14 | "dotnetRunMessages": true, 15 | "launchBrowser": true, 16 | "applicationUrl": "http://localhost:5122", 17 | "environmentVariables": { 18 | "ASPNETCORE_ENVIRONMENT": "Development" 19 | } 20 | }, 21 | "https": { 22 | "commandName": "Project", 23 | "dotnetRunMessages": true, 24 | "launchBrowser": true, 25 | "applicationUrl": "https://localhost:7100;http://localhost:5122", 26 | "environmentVariables": { 27 | "ASPNETCORE_ENVIRONMENT": "Development" 28 | } 29 | }, 30 | "IIS Express": { 31 | "commandName": "IISExpress", 32 | "launchBrowser": true, 33 | "environmentVariables": { 34 | "ASPNETCORE_ENVIRONMENT": "Development" 35 | } 36 | } 37 | } 38 | } 39 | -------------------------------------------------------------------------------- /TestingWithContainers.WebApp/TestingWithContainers.WebApp.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | net8.0 5 | enable 6 | enable 7 | Linux 8 | 9 | 10 | 11 | 12 | .dockerignore 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | -------------------------------------------------------------------------------- /TestingWithContainers.WebApp/appsettings.Development.json: -------------------------------------------------------------------------------- 1 | { 2 | "Logging": { 3 | "LogLevel": { 4 | "Default": "Information", 5 | "Microsoft.AspNetCore": "Warning" 6 | } 7 | } 8 | } 9 | -------------------------------------------------------------------------------- /TestingWithContainers.WebApp/appsettings.json: -------------------------------------------------------------------------------- 1 | { 2 | "Logging": { 3 | "LogLevel": { 4 | "Default": "Information", 5 | "Microsoft.AspNetCore": "Warning" 6 | } 7 | }, 8 | "AllowedHosts": "*" 9 | } 10 | -------------------------------------------------------------------------------- /TestingWithContainers.sln: -------------------------------------------------------------------------------- 1 |  2 | Microsoft Visual Studio Solution File, Format Version 12.00 3 | Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "TestingWithContainers", "TestingWithContainers\TestingWithContainers.csproj", "{3385B166-15A5-46CA-A811-D7A67F668298}" 4 | EndProject 5 | Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "TestingWithContainers.WebApp", "TestingWithContainers.WebApp\TestingWithContainers.WebApp.csproj", "{C0F4C39A-3375-4A64-973A-93D4CDD24A38}" 6 | EndProject 7 | Global 8 | GlobalSection(SolutionConfigurationPlatforms) = preSolution 9 | Debug|Any CPU = Debug|Any CPU 10 | Release|Any CPU = Release|Any CPU 11 | EndGlobalSection 12 | GlobalSection(ProjectConfigurationPlatforms) = postSolution 13 | {3385B166-15A5-46CA-A811-D7A67F668298}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 14 | {3385B166-15A5-46CA-A811-D7A67F668298}.Debug|Any CPU.Build.0 = Debug|Any CPU 15 | {3385B166-15A5-46CA-A811-D7A67F668298}.Release|Any CPU.ActiveCfg = Release|Any CPU 16 | {3385B166-15A5-46CA-A811-D7A67F668298}.Release|Any CPU.Build.0 = Release|Any CPU 17 | {C0F4C39A-3375-4A64-973A-93D4CDD24A38}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 18 | {C0F4C39A-3375-4A64-973A-93D4CDD24A38}.Debug|Any CPU.Build.0 = Debug|Any CPU 19 | {C0F4C39A-3375-4A64-973A-93D4CDD24A38}.Release|Any CPU.ActiveCfg = Release|Any CPU 20 | {C0F4C39A-3375-4A64-973A-93D4CDD24A38}.Release|Any CPU.Build.0 = Release|Any CPU 21 | EndGlobalSection 22 | EndGlobal 23 | -------------------------------------------------------------------------------- /TestingWithContainers/CustomContainerTest.cs: -------------------------------------------------------------------------------- 1 | using Docker.DotNet.Models; 2 | using DotNet.Testcontainers.Builders; 3 | using DotNet.Testcontainers.Containers; 4 | using DotNet.Testcontainers.Images; 5 | 6 | namespace TestingWithContainers; 7 | 8 | public class CustomContainerTest : IAsyncLifetime 9 | { 10 | private IFutureDockerImage image; 11 | private IContainer container; 12 | 13 | public async Task InitializeAsync() 14 | { 15 | image = new ImageFromDockerfileBuilder() 16 | .WithDockerfileDirectory(CommonDirectoryPath.GetSolutionDirectory(), string.Empty) 17 | .WithDockerfile("Dockerfile") 18 | .WithCleanUp(true) 19 | .Build(); 20 | 21 | // create image from Dockerfile 22 | await image.CreateAsync(); 23 | 24 | container = new ContainerBuilder() 25 | .WithImage(image) 26 | .WithPortBinding(80, assignRandomHostPort: true) 27 | // use environment variables to add configuration options 28 | .WithEnvironment("ASPNETCORE_URLS", "http://+:80") 29 | .WithWaitStrategy(Wait.ForUnixContainer().UntilHttpRequestIsSucceeded(r => r.ForPath("/"))) 30 | .Build(); 31 | 32 | // build container 33 | await container.StartAsync(); 34 | } 35 | 36 | public async Task DisposeAsync() 37 | { 38 | await image.DisposeAsync(); 39 | await container.DisposeAsync(); 40 | } 41 | 42 | [Fact] 43 | public async Task Can_Call_Endpoint() 44 | { 45 | var httpClient = new HttpClient(); 46 | 47 | var requestUri = 48 | new UriBuilder( 49 | Uri.UriSchemeHttp, 50 | container.Hostname, 51 | container.GetMappedPublicPort(80), 52 | "/" 53 | ).Uri; 54 | 55 | var expected = "Hello World!"; 56 | var actual = await httpClient.GetStringAsync(requestUri); 57 | 58 | Assert.Equal(expected, actual); 59 | } 60 | } -------------------------------------------------------------------------------- /TestingWithContainers/DatabaseContainerPerCollection.cs: -------------------------------------------------------------------------------- 1 | using Dapper; 2 | using JasperFx.Core; 3 | using Marten; 4 | using Npgsql; 5 | using Weasel.Core; 6 | using Xunit.Abstractions; 7 | 8 | namespace TestingWithContainers; 9 | 10 | [CollectionDefinition(nameof(DatabaseCollection))] 11 | public class DatabaseCollection : ICollectionFixture; 12 | 13 | public static class DatabaseContainerPerCollection 14 | { 15 | [Collection(nameof(DatabaseCollection))] 16 | public class First(DatabaseFixture fixture, ITestOutputHelper output) : IDisposable 17 | { 18 | [Fact] 19 | public async Task Database_Can_Run_Query() 20 | { 21 | await using NpgsqlConnection connection = new(fixture.ConnectionString); 22 | await connection.OpenAsync(); 23 | 24 | const int expected = 1; 25 | var actual = await connection.QueryFirstAsync("SELECT 1"); 26 | 27 | Assert.Equal(expected, actual); 28 | } 29 | 30 | [Fact] 31 | public async Task Database_Can_Select_DateTime() 32 | { 33 | await using NpgsqlConnection connection = new(fixture.ConnectionString); 34 | await connection.OpenAsync(); 35 | 36 | var actual = await connection.QueryFirstAsync("SELECT NOW()"); 37 | Assert.IsType(actual); 38 | } 39 | 40 | [Fact] 41 | public async Task Can_Store_Document_With_Marten() 42 | { 43 | await using NpgsqlConnection connection = new(fixture.ConnectionString); 44 | var store = DocumentStore.For(options => { 45 | options.Connection(fixture.ConnectionString); 46 | options.AutoCreateSchemaObjects = AutoCreate.All; 47 | }); 48 | 49 | int id; 50 | { 51 | await using var session = store.IdentitySession(); 52 | var person = new Person("Khalid"); 53 | session.Store(person); 54 | await session.SaveChangesAsync(); 55 | 56 | id = person.Id; 57 | } 58 | 59 | { 60 | await using var session = store.QuerySession(); 61 | var person = session.Query().FindFirst(p => p.Id == id); 62 | Assert.NotNull(person); 63 | } 64 | } 65 | 66 | public void Dispose() => output.WriteLine(fixture.ContainerId); 67 | } 68 | 69 | [Collection(nameof(DatabaseCollection))] 70 | public class Second(DatabaseFixture fixture, ITestOutputHelper output) : IDisposable 71 | { 72 | [Fact] 73 | public async Task Database_Can_Run_Query() 74 | { 75 | await using NpgsqlConnection connection = new(fixture.ConnectionString); 76 | await connection.OpenAsync(); 77 | 78 | output.WriteLine("Hi! 👋"); 79 | 80 | const int expected = 1; 81 | var actual = await connection.QueryFirstAsync("SELECT 1"); 82 | 83 | Assert.Equal(expected, actual); 84 | } 85 | 86 | [Fact] 87 | public async Task Database_Can_Select_DateTime() 88 | { 89 | await using NpgsqlConnection connection = new(fixture.ConnectionString); 90 | await connection.OpenAsync(); 91 | 92 | var actual = await connection.QueryFirstAsync("SELECT NOW()"); 93 | Assert.IsType(actual); 94 | } 95 | 96 | [Fact] 97 | public async Task Can_Store_Document_With_Marten() 98 | { 99 | await using NpgsqlConnection connection = new(fixture.ConnectionString); 100 | var store = DocumentStore.For(options => { 101 | options.Connection(fixture.ConnectionString); 102 | options.AutoCreateSchemaObjects = AutoCreate.All; 103 | }); 104 | 105 | int id; 106 | { 107 | await using var session = store.IdentitySession(); 108 | var person = new Person("Khalid"); 109 | session.Store(person); 110 | await session.SaveChangesAsync(); 111 | 112 | id = person.Id; 113 | } 114 | 115 | { 116 | await using var session = store.QuerySession(); 117 | var person = session.Query().FindFirst(p => p.Id == id); 118 | Assert.NotNull(person); 119 | } 120 | } 121 | 122 | public void Dispose() => output.WriteLine(fixture.ContainerId); 123 | } 124 | } -------------------------------------------------------------------------------- /TestingWithContainers/DatabaseContainerPerTest.cs: -------------------------------------------------------------------------------- 1 | using Dapper; 2 | using JasperFx.Core; 3 | using Marten; 4 | using Npgsql; 5 | using Testcontainers.PostgreSql; 6 | using Weasel.Core; 7 | using Xunit.Abstractions; 8 | 9 | namespace TestingWithContainers; 10 | 11 | public class DatabaseContainerPerTest(ITestOutputHelper output) 12 | : IAsyncLifetime 13 | { 14 | // this is called for each test, since each test 15 | // instantiates a new class instance 16 | private readonly PostgreSqlContainer container = 17 | new PostgreSqlBuilder() 18 | .Build(); 19 | 20 | private string connectionString = string.Empty; 21 | 22 | [Fact] 23 | public async Task Database_Can_Run_Query() 24 | { 25 | await using NpgsqlConnection connection = new(connectionString); 26 | await connection.OpenAsync(); 27 | 28 | const int expected = 1; 29 | var actual = await connection.QueryFirstAsync("SELECT 1"); 30 | 31 | Assert.Equal(expected, actual); 32 | } 33 | 34 | [Fact] 35 | public async Task Database_Can_Select_DateTime() 36 | { 37 | await using NpgsqlConnection connection = new(connectionString); 38 | await connection.OpenAsync(); 39 | 40 | var actual = await connection.QueryFirstAsync("SELECT NOW()"); 41 | Assert.IsType(actual); 42 | } 43 | 44 | [Fact] 45 | public async Task Can_Store_Document_With_Marten() 46 | { 47 | await using NpgsqlConnection connection = new(connectionString); 48 | var store = DocumentStore.For(options => { 49 | options.Connection(connectionString); 50 | options.AutoCreateSchemaObjects = AutoCreate.All; 51 | }); 52 | 53 | int id; 54 | { 55 | await using var session = store.IdentitySession(); 56 | var person = new Person("Khalid"); 57 | session.Store(person); 58 | await session.SaveChangesAsync(); 59 | 60 | id = person.Id; 61 | } 62 | 63 | { 64 | await using var session = store.QuerySession(); 65 | var person = session.Query().FindFirst(p => p.Id == id); 66 | Assert.NotNull(person); 67 | } 68 | } 69 | 70 | public async Task InitializeAsync() 71 | { 72 | await container.StartAsync(); 73 | connectionString = container.GetConnectionString(); 74 | output.WriteLine(container.Id); 75 | } 76 | 77 | public Task DisposeAsync() => container.StopAsync(); 78 | } -------------------------------------------------------------------------------- /TestingWithContainers/DatabaseContainerPerTestClass.cs: -------------------------------------------------------------------------------- 1 | using Dapper; 2 | using JasperFx.Core; 3 | using Marten; 4 | using Npgsql; 5 | using Weasel.Core; 6 | using Xunit.Abstractions; 7 | 8 | namespace TestingWithContainers; 9 | 10 | public class DatabaseContainerPerTestClass(DatabaseFixture fixture, ITestOutputHelper output) 11 | : IClassFixture, IDisposable 12 | { 13 | [Fact] 14 | public async Task Database_Can_Run_Query() 15 | { 16 | await using NpgsqlConnection connection = new(fixture.ConnectionString); 17 | await connection.OpenAsync(); 18 | 19 | output.WriteLine("Hi! 👋"); 20 | 21 | const int expected = 1; 22 | var actual = await connection.QueryFirstAsync("SELECT 1"); 23 | 24 | Assert.Equal(expected, actual); 25 | } 26 | 27 | [Fact] 28 | public async Task Database_Can_Select_DateTime() 29 | { 30 | await using NpgsqlConnection connection = new(fixture.ConnectionString); 31 | await connection.OpenAsync(); 32 | 33 | var actual = await connection.QueryFirstAsync("SELECT NOW()"); 34 | Assert.IsType(actual); 35 | } 36 | 37 | [Fact] 38 | public async Task Can_Store_Document_With_Marten() 39 | { 40 | await using NpgsqlConnection connection = new(fixture.ConnectionString); 41 | var store = DocumentStore.For(options => { 42 | options.Connection(fixture.ConnectionString); 43 | options.AutoCreateSchemaObjects = AutoCreate.All; 44 | }); 45 | 46 | int id; 47 | { 48 | await using var session = store.IdentitySession(); 49 | var person = new Person("Khalid"); 50 | session.Store(person); 51 | await session.SaveChangesAsync(); 52 | 53 | id = person.Id; 54 | } 55 | 56 | { 57 | await using var session = store.QuerySession(); 58 | var person = session.Query().FindFirst(p => p.Id == id); 59 | Assert.NotNull(person); 60 | } 61 | } 62 | 63 | public void Dispose() 64 | => output.WriteLine(fixture.ContainerId); 65 | } -------------------------------------------------------------------------------- /TestingWithContainers/DatabaseFixture.cs: -------------------------------------------------------------------------------- 1 | using Testcontainers.PostgreSql; 2 | 3 | namespace TestingWithContainers; 4 | 5 | // ReSharper disable once ClassNeverInstantiated.Global 6 | public class DatabaseFixture : IAsyncLifetime 7 | { 8 | private readonly PostgreSqlContainer container = 9 | new PostgreSqlBuilder() 10 | .Build(); 11 | 12 | public string ConnectionString => container.GetConnectionString(); 13 | public string ContainerId => $"{container.Id}"; 14 | 15 | public Task InitializeAsync() 16 | => container.StartAsync(); 17 | 18 | public Task DisposeAsync() 19 | => container.DisposeAsync().AsTask(); 20 | } -------------------------------------------------------------------------------- /TestingWithContainers/GlobalUsings.cs: -------------------------------------------------------------------------------- 1 | global using Xunit; -------------------------------------------------------------------------------- /TestingWithContainers/HttpTest.cs: -------------------------------------------------------------------------------- 1 | using DotNet.Testcontainers.Builders; 2 | using DotNet.Testcontainers.Containers; 3 | 4 | namespace TestingWithContainers; 5 | 6 | public class HttpTest : IAsyncLifetime 7 | { 8 | private readonly IContainer container; 9 | 10 | public HttpTest() 11 | { 12 | container = new ContainerBuilder() 13 | // Set the image for the container to "testcontainers/helloworld:1.1.0". 14 | .WithImage("testcontainers/helloworld:1.1.0") 15 | // Bind port 8080 of the container to a random port on the host. 16 | .WithPortBinding(8080, true) 17 | // Wait until the HTTP endpoint of the container is available. 18 | .WithWaitStrategy(Wait.ForUnixContainer().UntilHttpRequestIsSucceeded(r => r.ForPort(8080))) 19 | // Build the container configuration. 20 | .Build(); 21 | } 22 | 23 | [Fact] 24 | public async Task Can_Call_Endpoint() 25 | { 26 | var httpClient = new HttpClient(); 27 | 28 | var requestUri = 29 | new UriBuilder( 30 | Uri.UriSchemeHttp, 31 | container.Hostname, 32 | container.GetMappedPublicPort(8080), 33 | "uuid" 34 | ).Uri; 35 | 36 | var guid = await httpClient.GetStringAsync(requestUri); 37 | 38 | Assert.True(Guid.TryParse(guid, out _)); 39 | } 40 | 41 | public Task InitializeAsync() 42 | => container.StartAsync(); 43 | 44 | public Task DisposeAsync() 45 | => container.DisposeAsync().AsTask(); 46 | } -------------------------------------------------------------------------------- /TestingWithContainers/Person.cs: -------------------------------------------------------------------------------- 1 | namespace TestingWithContainers; 2 | 3 | // ReSharper disable once MemberCanBePrivate.Global 4 | public class Person(string name = "") 5 | { 6 | // ReSharper disable once UnusedAutoPropertyAccessor.Global 7 | public int Id { get; set; } 8 | // ReSharper disable once UnusedMember.Global 9 | public string Name { get; set; } = name; 10 | }; -------------------------------------------------------------------------------- /TestingWithContainers/TestingWithContainers.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | net8.0 5 | enable 6 | enable 7 | 8 | false 9 | true 10 | preview 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | runtime; build; native; contentfiles; analyzers; buildtransitive 23 | all 24 | 25 | 26 | runtime; build; native; contentfiles; analyzers; buildtransitive 27 | all 28 | 29 | 30 | 31 | 32 | 33 | 34 | 35 | 36 | -------------------------------------------------------------------------------- /TestingWithContainers/WebAppWithDatabase.cs: -------------------------------------------------------------------------------- 1 | using System.Net.Http.Json; 2 | using Dapper; 3 | using Microsoft.AspNetCore.Mvc.Testing; 4 | using Npgsql; 5 | 6 | namespace TestingWithContainers; 7 | 8 | public class WebAppWithDatabase(DatabaseFixture fixture) 9 | : IClassFixture, IAsyncLifetime 10 | { 11 | [Fact] 12 | public async Task Get_Information_From_Database_Endpoint() 13 | { 14 | var factory = new WebApplicationFactory() 15 | .WithWebHostBuilder(host => { 16 | // database connection from TestContainers 17 | host.UseSetting( 18 | "ConnectionStrings:database", 19 | fixture.ConnectionString 20 | ); 21 | }); 22 | 23 | var client = factory.CreateClient(); 24 | var actual = await client.GetFromJsonAsync("/database?make=Honda"); 25 | 26 | Assert.Equal(expected: "Civic", actual?.Model); 27 | } 28 | 29 | public async Task InitializeAsync() 30 | { 31 | var connection = new NpgsqlConnection(fixture.ConnectionString); 32 | // let's migrate a table here and insert values 33 | await connection.ExecuteAsync( 34 | // lang=sql 35 | """ 36 | DO $$ 37 | BEGIN 38 | IF NOT EXISTS (SELECT FROM pg_catalog.pg_tables WHERE schemaname = 'public' AND tablename = 'cars') THEN 39 | CREATE TABLE Cars ( 40 | id SERIAL PRIMARY KEY, 41 | make VARCHAR(255), 42 | model VARCHAR(255), 43 | year INT 44 | ); 45 | 46 | INSERT INTO Cars (make, model, year) VALUES 47 | ('Toyota', 'Corolla', 2020), 48 | ('Honda', 'Civic', 2020), 49 | ('Ford', 'Focus', 2020); 50 | END IF; 51 | END $$; 52 | """ 53 | ); 54 | } 55 | 56 | public Task DisposeAsync() => Task.CompletedTask; 57 | } -------------------------------------------------------------------------------- /global.json: -------------------------------------------------------------------------------- 1 | { 2 | "sdk": { 3 | "version": "8.0.0", 4 | "rollForward": "latestMajor", 5 | "allowPrerelease": true 6 | } 7 | } --------------------------------------------------------------------------------