├── .gitattributes ├── .gitignore ├── Directory.Build.props ├── LICENSE.txt ├── SampleAppWithTests.sln ├── global.json ├── readme.md ├── src ├── FrontEnd │ ├── .angulardoc.json │ ├── .editorconfig │ ├── .gitignore │ ├── .prettierrc.json │ ├── .vscode │ │ └── settings.json │ ├── README.md │ ├── angular.json │ ├── e2e │ │ ├── protractor.conf.js │ │ ├── src │ │ │ ├── app.e2e-spec.ts │ │ │ └── app.po.ts │ │ └── tsconfig.e2e.json │ ├── package-lock.json │ ├── package.json │ ├── src │ │ ├── app │ │ │ ├── app-routing.module.ts │ │ │ ├── app.component.html │ │ │ ├── app.component.scss │ │ │ ├── app.component.spec.ts │ │ │ ├── app.component.ts │ │ │ ├── app.module.ts │ │ │ ├── outsideRouter.service.ts │ │ │ └── product │ │ │ │ ├── product-create.component.html │ │ │ │ ├── product-create.component.scss │ │ │ │ ├── product-create.component.spec.ts │ │ │ │ ├── product-create.component.ts │ │ │ │ ├── product-routing.module.ts │ │ │ │ ├── product.component.html │ │ │ │ ├── product.component.scss │ │ │ │ ├── product.component.spec.ts │ │ │ │ ├── product.component.ts │ │ │ │ ├── product.module.ts │ │ │ │ └── product.ts │ │ ├── assets │ │ │ └── .gitkeep │ │ ├── browserslist │ │ ├── environments │ │ │ ├── environment.prod.ts │ │ │ └── environment.ts │ │ ├── favicon.ico │ │ ├── index.html │ │ ├── karma.conf.js │ │ ├── main.ts │ │ ├── polyfills.ts │ │ ├── styles.scss │ │ ├── test.ts │ │ ├── tsconfig.app.json │ │ ├── tsconfig.spec.json │ │ └── tslint.json │ ├── tsconfig.json │ └── tslint.json └── SampleApp │ ├── Controllers │ └── ProductsController.cs │ ├── Models │ ├── Product.cs │ ├── ProductsRepository.cs │ └── SampleAppContext.cs │ ├── Program.cs │ ├── Properties │ └── launchSettings.json │ ├── SampleApp.csproj │ ├── Startup.cs │ ├── appsettings.Development.json │ ├── appsettings.Test.json │ └── appsettings.json └── test ├── AcceptanceTests ├── AcceptanceTests.csproj ├── BaseAcceptanceTest.cs ├── DriverManager.cs ├── FrontendServer.cs ├── Pages │ ├── HomePage.cs │ ├── Page.cs │ └── ProductCreatePage.cs ├── ProjectFinder.cs ├── Setup.cs ├── Tests │ ├── ProductTests.cs │ └── SmokeTest.cs └── WaitElementExtension.cs ├── IntegrationTests ├── BaseIntegrationTest.cs ├── Generator.Product.cs ├── IntegrationTests.csproj ├── ProductControllerTests.cs ├── Setup.cs └── WebApplicationFactoryExtensions.cs └── UnitTests ├── Generator.Product.cs ├── ProductControllerTests.cs ├── ProductTests.cs └── UnitTests.csproj /.gitattributes: -------------------------------------------------------------------------------- 1 | ############################################################################### 2 | # Set default behavior to automatically normalize line endings. 3 | ############################################################################### 4 | * text=auto 5 | 6 | ############################################################################### 7 | # Set default behavior for command prompt diff. 8 | # 9 | # This is need for earlier builds of msysgit that does not have it on by 10 | # default for csharp files. 11 | # Note: This is only used by command line 12 | ############################################################################### 13 | #*.cs diff=csharp 14 | 15 | ############################################################################### 16 | # Set the merge driver for project and solution files 17 | # 18 | # Merging from the command prompt will add diff markers to the files if there 19 | # are conflicts (Merging from VS is not affected by the settings below, in VS 20 | # the diff markers are never inserted). Diff markers may cause the following 21 | # file extensions to fail to load in VS. An alternative would be to treat 22 | # these files as binary and thus will always conflict and require user 23 | # intervention with every merge. To do so, just uncomment the entries below 24 | ############################################################################### 25 | #*.sln merge=binary 26 | #*.csproj merge=binary 27 | #*.vbproj merge=binary 28 | #*.vcxproj merge=binary 29 | #*.vcproj merge=binary 30 | #*.dbproj merge=binary 31 | #*.fsproj merge=binary 32 | #*.lsproj merge=binary 33 | #*.wixproj merge=binary 34 | #*.modelproj merge=binary 35 | #*.sqlproj merge=binary 36 | #*.wwaproj merge=binary 37 | 38 | ############################################################################### 39 | # behavior for image files 40 | # 41 | # image files are treated as binary by default. 42 | ############################################################################### 43 | #*.jpg binary 44 | #*.png binary 45 | #*.gif binary 46 | 47 | ############################################################################### 48 | # diff behavior for common document formats 49 | # 50 | # Convert binary document formats to text before diffing them. This feature 51 | # is only available from the command line. Turn it on by uncommenting the 52 | # entries below. 53 | ############################################################################### 54 | #*.doc diff=astextplain 55 | #*.DOC diff=astextplain 56 | #*.docx diff=astextplain 57 | #*.DOCX diff=astextplain 58 | #*.dot diff=astextplain 59 | #*.DOT diff=astextplain 60 | #*.pdf diff=astextplain 61 | #*.PDF diff=astextplain 62 | #*.rtf diff=astextplain 63 | #*.RTF diff=astextplain 64 | -------------------------------------------------------------------------------- /.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 | *.rsuser 8 | *.suo 9 | *.user 10 | *.userosscache 11 | *.sln.docstates 12 | 13 | # User-specific files (MonoDevelop/Xamarin Studio) 14 | *.userprefs 15 | 16 | # Build results 17 | [Dd]ebug/ 18 | [Dd]ebugPublic/ 19 | [Rr]elease/ 20 | [Rr]eleases/ 21 | x64/ 22 | x86/ 23 | [Aa][Rr][Mm]/ 24 | [Aa][Rr][Mm]64/ 25 | bld/ 26 | [Bb]in/ 27 | [Oo]bj/ 28 | [Ll]og/ 29 | 30 | # Visual Studio 2015/2017 cache/options directory 31 | .vs/ 32 | # Uncomment if you have tasks that create the project's static files in wwwroot 33 | #wwwroot/ 34 | 35 | # Visual Studio 2017 auto generated files 36 | Generated\ Files/ 37 | 38 | # MSTest test Results 39 | [Tt]est[Rr]esult*/ 40 | [Bb]uild[Ll]og.* 41 | 42 | # NUNIT 43 | *.VisualState.xml 44 | TestResult.xml 45 | 46 | # Build Results of an ATL Project 47 | [Dd]ebugPS/ 48 | [Rr]eleasePS/ 49 | dlldata.c 50 | 51 | # Benchmark Results 52 | BenchmarkDotNet.Artifacts/ 53 | 54 | # .NET Core 55 | project.lock.json 56 | project.fragment.lock.json 57 | artifacts/ 58 | 59 | # StyleCop 60 | StyleCopReport.xml 61 | 62 | # Files built by Visual Studio 63 | *_i.c 64 | *_p.c 65 | *_h.h 66 | *.ilk 67 | *.meta 68 | *.obj 69 | *.iobj 70 | *.pch 71 | *.pdb 72 | *.ipdb 73 | *.pgc 74 | *.pgd 75 | *.rsp 76 | *.sbr 77 | *.tlb 78 | *.tli 79 | *.tlh 80 | *.tmp 81 | *.tmp_proj 82 | *_wpftmp.csproj 83 | *.log 84 | *.vspscc 85 | *.vssscc 86 | .builds 87 | *.pidb 88 | *.svclog 89 | *.scc 90 | 91 | # Chutzpah Test files 92 | _Chutzpah* 93 | 94 | # Visual C++ cache files 95 | ipch/ 96 | *.aps 97 | *.ncb 98 | *.opendb 99 | *.opensdf 100 | *.sdf 101 | *.cachefile 102 | *.VC.db 103 | *.VC.VC.opendb 104 | 105 | # Visual Studio profiler 106 | *.psess 107 | *.vsp 108 | *.vspx 109 | *.sap 110 | 111 | # Visual Studio Trace Files 112 | *.e2e 113 | 114 | # TFS 2012 Local Workspace 115 | $tf/ 116 | 117 | # Guidance Automation Toolkit 118 | *.gpState 119 | 120 | # ReSharper is a .NET coding add-in 121 | _ReSharper*/ 122 | *.[Rr]e[Ss]harper 123 | *.DotSettings.user 124 | 125 | # JustCode is a .NET coding add-in 126 | .JustCode 127 | 128 | # TeamCity is a build add-in 129 | _TeamCity* 130 | 131 | # DotCover is a Code Coverage Tool 132 | *.dotCover 133 | 134 | # AxoCover is a Code Coverage Tool 135 | .axoCover/* 136 | !.axoCover/settings.json 137 | 138 | # Visual Studio code coverage results 139 | *.coverage 140 | *.coveragexml 141 | 142 | # NCrunch 143 | _NCrunch_* 144 | .*crunch*.local.xml 145 | nCrunchTemp_* 146 | 147 | # MightyMoose 148 | *.mm.* 149 | AutoTest.Net/ 150 | 151 | # Web workbench (sass) 152 | .sass-cache/ 153 | 154 | # Installshield output folder 155 | [Ee]xpress/ 156 | 157 | # DocProject is a documentation generator add-in 158 | DocProject/buildhelp/ 159 | DocProject/Help/*.HxT 160 | DocProject/Help/*.HxC 161 | DocProject/Help/*.hhc 162 | DocProject/Help/*.hhk 163 | DocProject/Help/*.hhp 164 | DocProject/Help/Html2 165 | DocProject/Help/html 166 | 167 | # Click-Once directory 168 | publish/ 169 | 170 | # Publish Web Output 171 | *.[Pp]ublish.xml 172 | *.azurePubxml 173 | # Note: Comment the next line if you want to checkin your web deploy settings, 174 | # but database connection strings (with potential passwords) will be unencrypted 175 | *.pubxml 176 | *.publishproj 177 | 178 | # Microsoft Azure Web App publish settings. Comment the next line if you want to 179 | # checkin your Azure Web App publish settings, but sensitive information contained 180 | # in these scripts will be unencrypted 181 | PublishScripts/ 182 | 183 | # NuGet Packages 184 | *.nupkg 185 | # The packages folder can be ignored because of Package Restore 186 | **/[Pp]ackages/* 187 | # except build/, which is used as an MSBuild target. 188 | !**/[Pp]ackages/build/ 189 | # Uncomment if necessary however generally it will be regenerated when needed 190 | #!**/[Pp]ackages/repositories.config 191 | # NuGet v3's project.json files produces more ignorable files 192 | *.nuget.props 193 | *.nuget.targets 194 | 195 | # Microsoft Azure Build Output 196 | csx/ 197 | *.build.csdef 198 | 199 | # Microsoft Azure Emulator 200 | ecf/ 201 | rcf/ 202 | 203 | # Windows Store app package directories and files 204 | AppPackages/ 205 | BundleArtifacts/ 206 | Package.StoreAssociation.xml 207 | _pkginfo.txt 208 | *.appx 209 | 210 | # Visual Studio cache files 211 | # files ending in .cache can be ignored 212 | *.[Cc]ache 213 | # but keep track of directories ending in .cache 214 | !?*.[Cc]ache/ 215 | 216 | # Others 217 | ClientBin/ 218 | ~$* 219 | *~ 220 | *.dbmdl 221 | *.dbproj.schemaview 222 | *.jfm 223 | *.pfx 224 | *.publishsettings 225 | orleans.codegen.cs 226 | 227 | # Including strong name files can present a security risk 228 | # (https://github.com/github/gitignore/pull/2483#issue-259490424) 229 | #*.snk 230 | 231 | # Since there are multiple workflows, uncomment next line to ignore bower_components 232 | # (https://github.com/github/gitignore/pull/1529#issuecomment-104372622) 233 | #bower_components/ 234 | 235 | # RIA/Silverlight projects 236 | Generated_Code/ 237 | 238 | # Backup & report files from converting an old project file 239 | # to a newer Visual Studio version. Backup files are not needed, 240 | # because we have git ;-) 241 | _UpgradeReport_Files/ 242 | Backup*/ 243 | UpgradeLog*.XML 244 | UpgradeLog*.htm 245 | ServiceFabricBackup/ 246 | *.rptproj.bak 247 | 248 | # SQL Server files 249 | *.mdf 250 | *.ldf 251 | *.ndf 252 | 253 | # Business Intelligence projects 254 | *.rdl.data 255 | *.bim.layout 256 | *.bim_*.settings 257 | *.rptproj.rsuser 258 | *- Backup*.rdl 259 | 260 | # Microsoft Fakes 261 | FakesAssemblies/ 262 | 263 | # GhostDoc plugin setting file 264 | *.GhostDoc.xml 265 | 266 | # Node.js Tools for Visual Studio 267 | .ntvs_analysis.dat 268 | node_modules/ 269 | 270 | # Visual Studio 6 build log 271 | *.plg 272 | 273 | # Visual Studio 6 workspace options file 274 | *.opt 275 | 276 | # Visual Studio 6 auto-generated workspace file (contains which files were open etc.) 277 | *.vbw 278 | 279 | # Visual Studio LightSwitch build output 280 | **/*.HTMLClient/GeneratedArtifacts 281 | **/*.DesktopClient/GeneratedArtifacts 282 | **/*.DesktopClient/ModelManifest.xml 283 | **/*.Server/GeneratedArtifacts 284 | **/*.Server/ModelManifest.xml 285 | _Pvt_Extensions 286 | 287 | # Paket dependency manager 288 | .paket/paket.exe 289 | paket-files/ 290 | 291 | # FAKE - F# Make 292 | .fake/ 293 | 294 | # JetBrains Rider 295 | .idea/ 296 | *.sln.iml 297 | 298 | # CodeRush personal settings 299 | .cr/personal 300 | 301 | # Python Tools for Visual Studio (PTVS) 302 | __pycache__/ 303 | *.pyc 304 | 305 | # Cake - Uncomment if you are using it 306 | # tools/** 307 | # !tools/packages.config 308 | 309 | # Tabs Studio 310 | *.tss 311 | 312 | # Telerik's JustMock configuration file 313 | *.jmconfig 314 | 315 | # BizTalk build output 316 | *.btp.cs 317 | *.btm.cs 318 | *.odx.cs 319 | *.xsd.cs 320 | 321 | # OpenCover UI analysis results 322 | OpenCover/ 323 | 324 | # Azure Stream Analytics local run output 325 | ASALocalRun/ 326 | 327 | # MSBuild Binary and Structured Log 328 | *.binlog 329 | 330 | # NVidia Nsight GPU debugger configuration file 331 | *.nvuser 332 | 333 | # MFractors (Xamarin productivity tool) working folder 334 | .mfractor/ 335 | 336 | # Local History for Visual Studio 337 | .localhistory/ 338 | 339 | # BeatPulse healthcheck temp database 340 | healthchecksdb -------------------------------------------------------------------------------- /Directory.Build.props: -------------------------------------------------------------------------------- 1 | 2 | 3 | latest 4 | 5 | 6 | -------------------------------------------------------------------------------- /LICENSE.txt: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "{}" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright 2014 Giovanni Bassi and Elemar Jr. 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /SampleAppWithTests.sln: -------------------------------------------------------------------------------- 1 |  2 | Microsoft Visual Studio Solution File, Format Version 12.00 3 | # Visual Studio Version 16 4 | VisualStudioVersion = 16.0.28803.156 5 | MinimumVisualStudioVersion = 10.0.40219.1 6 | Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "src", "src", "{F98F059C-841C-4EE8-8817-53D75E388212}" 7 | EndProject 8 | Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "test", "test", "{559F5A56-847C-4BA7-A815-4AF14A9F17F3}" 9 | EndProject 10 | Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "SampleApp", "src\SampleApp\SampleApp.csproj", "{DF4034D6-624F-47FD-B655-7B8DBC63225B}" 11 | EndProject 12 | Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "UnitTests", "test\UnitTests\UnitTests.csproj", "{D0CE5738-CDBC-4B71-8EA1-7052D5932DD3}" 13 | EndProject 14 | Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "IntegrationTests", "test\IntegrationTests\IntegrationTests.csproj", "{89B5D8A4-859C-4F2B-B431-8F45C3F4FA0B}" 15 | EndProject 16 | Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "AcceptanceTests", "test\AcceptanceTests\AcceptanceTests.csproj", "{65C91A36-7339-4EC9-81FC-DED0106E3082}" 17 | EndProject 18 | Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Solution Items", "Solution Items", "{0CCDDB91-0B6C-4451-9BA9-EE7FA04904E9}" 19 | ProjectSection(SolutionItems) = preProject 20 | .gitattributes = .gitattributes 21 | .gitignore = .gitignore 22 | Directory.Build.props = Directory.Build.props 23 | global.json = global.json 24 | readme.md = readme.md 25 | EndProjectSection 26 | EndProject 27 | Global 28 | GlobalSection(SolutionConfigurationPlatforms) = preSolution 29 | Debug|Any CPU = Debug|Any CPU 30 | Release|Any CPU = Release|Any CPU 31 | EndGlobalSection 32 | GlobalSection(ProjectConfigurationPlatforms) = postSolution 33 | {DF4034D6-624F-47FD-B655-7B8DBC63225B}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 34 | {DF4034D6-624F-47FD-B655-7B8DBC63225B}.Debug|Any CPU.Build.0 = Debug|Any CPU 35 | {DF4034D6-624F-47FD-B655-7B8DBC63225B}.Release|Any CPU.ActiveCfg = Release|Any CPU 36 | {DF4034D6-624F-47FD-B655-7B8DBC63225B}.Release|Any CPU.Build.0 = Release|Any CPU 37 | {D0CE5738-CDBC-4B71-8EA1-7052D5932DD3}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 38 | {D0CE5738-CDBC-4B71-8EA1-7052D5932DD3}.Debug|Any CPU.Build.0 = Debug|Any CPU 39 | {D0CE5738-CDBC-4B71-8EA1-7052D5932DD3}.Release|Any CPU.ActiveCfg = Release|Any CPU 40 | {D0CE5738-CDBC-4B71-8EA1-7052D5932DD3}.Release|Any CPU.Build.0 = Release|Any CPU 41 | {89B5D8A4-859C-4F2B-B431-8F45C3F4FA0B}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 42 | {89B5D8A4-859C-4F2B-B431-8F45C3F4FA0B}.Debug|Any CPU.Build.0 = Debug|Any CPU 43 | {89B5D8A4-859C-4F2B-B431-8F45C3F4FA0B}.Release|Any CPU.ActiveCfg = Release|Any CPU 44 | {89B5D8A4-859C-4F2B-B431-8F45C3F4FA0B}.Release|Any CPU.Build.0 = Release|Any CPU 45 | {65C91A36-7339-4EC9-81FC-DED0106E3082}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 46 | {65C91A36-7339-4EC9-81FC-DED0106E3082}.Debug|Any CPU.Build.0 = Debug|Any CPU 47 | {65C91A36-7339-4EC9-81FC-DED0106E3082}.Release|Any CPU.ActiveCfg = Release|Any CPU 48 | {65C91A36-7339-4EC9-81FC-DED0106E3082}.Release|Any CPU.Build.0 = Release|Any CPU 49 | EndGlobalSection 50 | GlobalSection(SolutionProperties) = preSolution 51 | HideSolutionNode = FALSE 52 | EndGlobalSection 53 | GlobalSection(NestedProjects) = preSolution 54 | {DF4034D6-624F-47FD-B655-7B8DBC63225B} = {F98F059C-841C-4EE8-8817-53D75E388212} 55 | {D0CE5738-CDBC-4B71-8EA1-7052D5932DD3} = {559F5A56-847C-4BA7-A815-4AF14A9F17F3} 56 | {89B5D8A4-859C-4F2B-B431-8F45C3F4FA0B} = {559F5A56-847C-4BA7-A815-4AF14A9F17F3} 57 | {65C91A36-7339-4EC9-81FC-DED0106E3082} = {559F5A56-847C-4BA7-A815-4AF14A9F17F3} 58 | EndGlobalSection 59 | GlobalSection(ExtensibilityGlobals) = postSolution 60 | SolutionGuid = {AF3BB9E0-A1F5-402C-99B0-5944C30298D3} 61 | EndGlobalSection 62 | EndGlobal 63 | -------------------------------------------------------------------------------- /global.json: -------------------------------------------------------------------------------- 1 | { 2 | "sdk": { 3 | "version": "2.2.104" 4 | } 5 | } 6 | -------------------------------------------------------------------------------- /readme.md: -------------------------------------------------------------------------------- 1 | # Sample ASP.NET Core + Angular project with tests 2 | 3 | A project to help demonstrate how to do unit, integration and acceptance 4 | tests with an web api project using ASP.NET Core and Angular 7 front end. 5 | 6 | ## Running the tests 7 | 8 | From the terminal, in the project root, simply run: 9 | 10 | ```shell 11 | dotnet test 12 | ``` 13 | 14 | Or run them from each test project directory (on the `test` subdir) or 15 | directly from Visual Studio. 16 | 17 | ## Running the api app 18 | 19 | Run `dotnet run` from `src/SampleApp`. 20 | 21 | ## Running the web front end 22 | 23 | First run the api app, then run `npm start` from `src/FrontEnd`. 24 | 25 | ## Supported .NET SDK and CLI versions 26 | 27 | This was compiled with the v2.2.2 sdk (dotnet version 2.2.104). Anything after 28 | that should run. To try different versions, simply remove `global.json` from the root. 29 | 30 | [Download the SDK](https://dotnet.microsoft.com/download/dotnet-core/2.2). 31 | 32 | 33 | ## Contributing 34 | 35 | Questions, comments, bug reports, and pull requests are all welcome. Submit them at 36 | [the project on GitHub](https://github.com/giggio-samples/aspnetcore-tests-sample). 37 | 38 | Bug reports that include steps-to-reproduce (including code) are the 39 | best. Even better, make them in the form of pull requests. 40 | 41 | ## Author 42 | 43 | [Giovanni Bassi](https://github.com/giggio) 44 | 45 | ## License 46 | 47 | Licensed under the Apache License, Version 2.0. 48 | -------------------------------------------------------------------------------- /src/FrontEnd/.angulardoc.json: -------------------------------------------------------------------------------- 1 | { 2 | "repoId": "a5da2baa-14fe-48e0-aeaa-a002b751a7d1", 3 | "lastSync": 0 4 | } -------------------------------------------------------------------------------- /src/FrontEnd/.editorconfig: -------------------------------------------------------------------------------- 1 | root = true 2 | 3 | [*] 4 | charset = utf-8 5 | indent_style = space 6 | indent_size = 2 7 | insert_final_newline = true 8 | trim_trailing_whitespace = true 9 | 10 | [*.md] 11 | max_line_length = off 12 | trim_trailing_whitespace = false 13 | -------------------------------------------------------------------------------- /src/FrontEnd/.gitignore: -------------------------------------------------------------------------------- 1 | # See http://help.github.com/ignore-files/ for more about ignoring files. 2 | 3 | # compiled output 4 | /dist 5 | /tmp 6 | /out-tsc 7 | # Only exists if Bazel was run 8 | /bazel-out 9 | 10 | # dependencies 11 | /node_modules 12 | 13 | # profiling files 14 | chrome-profiler-events.json 15 | speed-measure-plugin.json 16 | 17 | # IDEs and editors 18 | /.idea 19 | .project 20 | .classpath 21 | .c9/ 22 | *.launch 23 | .settings/ 24 | *.sublime-workspace 25 | 26 | # IDE - VSCode 27 | .vscode/* 28 | !.vscode/settings.json 29 | !.vscode/tasks.json 30 | !.vscode/launch.json 31 | !.vscode/extensions.json 32 | .history/* 33 | 34 | # misc 35 | /.sass-cache 36 | /connect.lock 37 | /coverage 38 | /libpeerconnection.log 39 | npm-debug.log 40 | yarn-error.log 41 | testem.log 42 | /typings 43 | 44 | # System Files 45 | .DS_Store 46 | Thumbs.db 47 | -------------------------------------------------------------------------------- /src/FrontEnd/.prettierrc.json: -------------------------------------------------------------------------------- 1 | { 2 | "$schema": "http://json.schemastore.org/prettierrc", 3 | "semi": true, 4 | "singleQuote": true, 5 | "bracketSpacing": true, 6 | "arrowParens": "avoid" 7 | } 8 | -------------------------------------------------------------------------------- /src/FrontEnd/.vscode/settings.json: -------------------------------------------------------------------------------- 1 | { 2 | } -------------------------------------------------------------------------------- /src/FrontEnd/README.md: -------------------------------------------------------------------------------- 1 | # FrontEnd 2 | 3 | This project was generated with [Angular CLI](https://github.com/angular/angular-cli) version 7.3.8. 4 | 5 | ## Development server 6 | 7 | Run `ng serve` for a dev server. Navigate to `http://localhost:4200/`. The app will automatically reload if you change any of the source files. 8 | 9 | ## Code scaffolding 10 | 11 | Run `ng generate component component-name` to generate a new component. You can also use `ng generate directive|pipe|service|class|guard|interface|enum|module`. 12 | 13 | ## Build 14 | 15 | Run `ng build` to build the project. The build artifacts will be stored in the `dist/` directory. Use the `--prod` flag for a production build. 16 | 17 | ## Running unit tests 18 | 19 | Run `ng test` to execute the unit tests via [Karma](https://karma-runner.github.io). 20 | 21 | ## Running end-to-end tests 22 | 23 | Run `ng e2e` to execute the end-to-end tests via [Protractor](http://www.protractortest.org/). 24 | 25 | ## Further help 26 | 27 | To get more help on the Angular CLI use `ng help` or go check out the [Angular CLI README](https://github.com/angular/angular-cli/blob/master/README.md). 28 | -------------------------------------------------------------------------------- /src/FrontEnd/angular.json: -------------------------------------------------------------------------------- 1 | { 2 | "$schema": "./node_modules/@angular/cli/lib/config/schema.json", 3 | "version": 1, 4 | "newProjectRoot": "projects", 5 | "projects": { 6 | "FrontEnd": { 7 | "root": "", 8 | "sourceRoot": "src", 9 | "projectType": "application", 10 | "prefix": "app", 11 | "schematics": { 12 | "@schematics/angular:component": { 13 | "style": "scss" 14 | } 15 | }, 16 | "architect": { 17 | "build": { 18 | "builder": "@angular-devkit/build-angular:browser", 19 | "options": { 20 | "outputPath": "dist/FrontEnd", 21 | "index": "src/index.html", 22 | "main": "src/main.ts", 23 | "polyfills": "src/polyfills.ts", 24 | "tsConfig": "src/tsconfig.app.json", 25 | "assets": [ 26 | "src/favicon.ico", 27 | "src/assets" 28 | ], 29 | "styles": [ 30 | "src/styles.scss" 31 | ], 32 | "scripts": [], 33 | "es5BrowserSupport": true 34 | }, 35 | "configurations": { 36 | "production": { 37 | "fileReplacements": [ 38 | { 39 | "replace": "src/environments/environment.ts", 40 | "with": "src/environments/environment.prod.ts" 41 | } 42 | ], 43 | "optimization": true, 44 | "outputHashing": "all", 45 | "sourceMap": false, 46 | "extractCss": true, 47 | "namedChunks": false, 48 | "aot": true, 49 | "extractLicenses": true, 50 | "vendorChunk": false, 51 | "buildOptimizer": true, 52 | "budgets": [ 53 | { 54 | "type": "initial", 55 | "maximumWarning": "2mb", 56 | "maximumError": "5mb" 57 | } 58 | ] 59 | } 60 | } 61 | }, 62 | "serve": { 63 | "builder": "@angular-devkit/build-angular:dev-server", 64 | "options": { 65 | "browserTarget": "FrontEnd:build" 66 | }, 67 | "configurations": { 68 | "production": { 69 | "browserTarget": "FrontEnd:build:production" 70 | } 71 | } 72 | }, 73 | "extract-i18n": { 74 | "builder": "@angular-devkit/build-angular:extract-i18n", 75 | "options": { 76 | "browserTarget": "FrontEnd:build" 77 | } 78 | }, 79 | "test": { 80 | "builder": "@angular-devkit/build-angular:karma", 81 | "options": { 82 | "main": "src/test.ts", 83 | "polyfills": "src/polyfills.ts", 84 | "tsConfig": "src/tsconfig.spec.json", 85 | "karmaConfig": "src/karma.conf.js", 86 | "styles": [ 87 | "src/styles.scss" 88 | ], 89 | "scripts": [], 90 | "assets": [ 91 | "src/favicon.ico", 92 | "src/assets" 93 | ] 94 | } 95 | }, 96 | "lint": { 97 | "builder": "@angular-devkit/build-angular:tslint", 98 | "options": { 99 | "tsConfig": [ 100 | "src/tsconfig.app.json", 101 | "src/tsconfig.spec.json" 102 | ], 103 | "exclude": [ 104 | "**/node_modules/**" 105 | ] 106 | } 107 | } 108 | } 109 | }, 110 | "FrontEnd-e2e": { 111 | "root": "e2e/", 112 | "projectType": "application", 113 | "prefix": "", 114 | "architect": { 115 | "e2e": { 116 | "builder": "@angular-devkit/build-angular:protractor", 117 | "options": { 118 | "protractorConfig": "e2e/protractor.conf.js", 119 | "devServerTarget": "FrontEnd:serve" 120 | }, 121 | "configurations": { 122 | "production": { 123 | "devServerTarget": "FrontEnd:serve:production" 124 | } 125 | } 126 | }, 127 | "lint": { 128 | "builder": "@angular-devkit/build-angular:tslint", 129 | "options": { 130 | "tsConfig": "e2e/tsconfig.e2e.json", 131 | "exclude": [ 132 | "**/node_modules/**" 133 | ] 134 | } 135 | } 136 | } 137 | } 138 | }, 139 | "defaultProject": "FrontEnd" 140 | } -------------------------------------------------------------------------------- /src/FrontEnd/e2e/protractor.conf.js: -------------------------------------------------------------------------------- 1 | // Protractor configuration file, see link for more information 2 | // https://github.com/angular/protractor/blob/master/lib/config.ts 3 | 4 | const { SpecReporter } = require('jasmine-spec-reporter'); 5 | 6 | exports.config = { 7 | allScriptsTimeout: 11000, 8 | specs: [ 9 | './src/**/*.e2e-spec.ts' 10 | ], 11 | capabilities: { 12 | 'browserName': 'chrome' 13 | }, 14 | directConnect: true, 15 | baseUrl: 'http://localhost:4200/', 16 | framework: 'jasmine', 17 | jasmineNodeOpts: { 18 | showColors: true, 19 | defaultTimeoutInterval: 30000, 20 | print: function() {} 21 | }, 22 | onPrepare() { 23 | require('ts-node').register({ 24 | project: require('path').join(__dirname, './tsconfig.e2e.json') 25 | }); 26 | jasmine.getEnv().addReporter(new SpecReporter({ spec: { displayStacktrace: true } })); 27 | } 28 | }; -------------------------------------------------------------------------------- /src/FrontEnd/e2e/src/app.e2e-spec.ts: -------------------------------------------------------------------------------- 1 | import { AppPage } from './app.po'; 2 | import { browser, logging } from 'protractor'; 3 | 4 | describe('workspace-project App', () => { 5 | let page: AppPage; 6 | 7 | beforeEach(() => { 8 | page = new AppPage(); 9 | }); 10 | 11 | it('should display welcome message', () => { 12 | page.navigateTo(); 13 | expect(page.getTitleText()).toEqual('Welcome to FrontEnd!'); 14 | }); 15 | 16 | afterEach(async () => { 17 | // Assert that there are no errors emitted from the browser 18 | const logs = await browser.manage().logs().get(logging.Type.BROWSER); 19 | expect(logs).not.toContain(jasmine.objectContaining({ 20 | level: logging.Level.SEVERE, 21 | } as logging.Entry)); 22 | }); 23 | }); 24 | -------------------------------------------------------------------------------- /src/FrontEnd/e2e/src/app.po.ts: -------------------------------------------------------------------------------- 1 | import { browser, by, element } from 'protractor'; 2 | 3 | export class AppPage { 4 | navigateTo() { 5 | return browser.get(browser.baseUrl) as Promise; 6 | } 7 | 8 | getTitleText() { 9 | return element(by.css('app-root h1')).getText() as Promise; 10 | } 11 | } 12 | -------------------------------------------------------------------------------- /src/FrontEnd/e2e/tsconfig.e2e.json: -------------------------------------------------------------------------------- 1 | { 2 | "extends": "../tsconfig.json", 3 | "compilerOptions": { 4 | "outDir": "../out-tsc/app", 5 | "module": "commonjs", 6 | "target": "es5", 7 | "types": [ 8 | "jasmine", 9 | "jasminewd2", 10 | "node" 11 | ] 12 | } 13 | } -------------------------------------------------------------------------------- /src/FrontEnd/package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "front-end", 3 | "version": "0.0.0", 4 | "scripts": { 5 | "ng": "ng", 6 | "start": "ng serve", 7 | "start:test": "http-webnode -n index -p 7200 ./dist/FrontEnd/", 8 | "build": "ng build", 9 | "build:aot": "ng build --prod --configuration production", 10 | "test": "ng test", 11 | "lint": "ng lint", 12 | "e2e": "ng e2e" 13 | }, 14 | "private": true, 15 | "dependencies": { 16 | "@angular/animations": "~7.2.0", 17 | "@angular/common": "~7.2.0", 18 | "@angular/compiler": "~7.2.0", 19 | "@angular/core": "~7.2.0", 20 | "@angular/forms": "~7.2.0", 21 | "@angular/platform-browser": "~7.2.0", 22 | "@angular/platform-browser-dynamic": "~7.2.0", 23 | "@angular/router": "~7.2.0", 24 | "core-js": "^2.5.4", 25 | "rxjs": "~6.3.3", 26 | "tslib": "^1.9.0", 27 | "zone.js": "~0.8.26" 28 | }, 29 | "devDependencies": { 30 | "@angular-devkit/build-angular": "~0.13.0", 31 | "@angular/cli": "~7.3.8", 32 | "@angular/compiler-cli": "~7.2.0", 33 | "@angular/language-service": "~7.2.0", 34 | "@types/jasmine": "~2.8.8", 35 | "@types/jasminewd2": "~2.0.3", 36 | "@types/node": "~8.9.4", 37 | "codelyzer": "~4.5.0", 38 | "http-webnode": "^1.0.1", 39 | "jasmine-core": "~2.99.1", 40 | "jasmine-spec-reporter": "~4.2.1", 41 | "karma": "~4.0.0", 42 | "karma-chrome-launcher": "~2.2.0", 43 | "karma-coverage-istanbul-reporter": "~2.0.1", 44 | "karma-jasmine": "~1.1.2", 45 | "karma-jasmine-html-reporter": "^0.2.2", 46 | "protractor": "~5.4.0", 47 | "ts-node": "~7.0.0", 48 | "tslint": "~5.11.0", 49 | "typescript": "~3.2.2" 50 | } 51 | } 52 | -------------------------------------------------------------------------------- /src/FrontEnd/src/app/app-routing.module.ts: -------------------------------------------------------------------------------- 1 | import { NgModule } from '@angular/core'; 2 | import { Routes, RouterModule } from '@angular/router'; 3 | 4 | const routes: Routes = []; 5 | 6 | @NgModule({ 7 | imports: [RouterModule.forRoot(routes)], 8 | exports: [RouterModule] 9 | }) 10 | export class AppRoutingModule { } 11 | -------------------------------------------------------------------------------- /src/FrontEnd/src/app/app.component.html: -------------------------------------------------------------------------------- 1 |
2 |

3 | Welcome to {{ title }}! 4 |

5 |
6 |
7 | Menu: 8 | 11 |
12 |
13 | 14 |
15 | -------------------------------------------------------------------------------- /src/FrontEnd/src/app/app.component.scss: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/giggio-samples/aspnetcore-tests-sample/ca06516470e5105e5aa6b5c73ffaeff58598abf3/src/FrontEnd/src/app/app.component.scss -------------------------------------------------------------------------------- /src/FrontEnd/src/app/app.component.spec.ts: -------------------------------------------------------------------------------- 1 | import { TestBed, async } from '@angular/core/testing'; 2 | import { RouterTestingModule } from '@angular/router/testing'; 3 | import { AppComponent } from './app.component'; 4 | 5 | describe('AppComponent', () => { 6 | beforeEach(async(() => { 7 | TestBed.configureTestingModule({ 8 | imports: [ 9 | RouterTestingModule 10 | ], 11 | declarations: [ 12 | AppComponent 13 | ], 14 | }).compileComponents(); 15 | })); 16 | 17 | it('should create the app', () => { 18 | const fixture = TestBed.createComponent(AppComponent); 19 | const app = fixture.debugElement.componentInstance; 20 | expect(app).toBeTruthy(); 21 | }); 22 | 23 | it(`should have as title 'FrontEnd'`, () => { 24 | const fixture = TestBed.createComponent(AppComponent); 25 | const app = fixture.debugElement.componentInstance; 26 | expect(app.title).toEqual('FrontEnd'); 27 | }); 28 | 29 | it('should render title in a h1 tag', () => { 30 | const fixture = TestBed.createComponent(AppComponent); 31 | fixture.detectChanges(); 32 | const compiled = fixture.debugElement.nativeElement; 33 | expect(compiled.querySelector('h1').textContent).toContain('Welcome to FrontEnd!'); 34 | }); 35 | }); 36 | -------------------------------------------------------------------------------- /src/FrontEnd/src/app/app.component.ts: -------------------------------------------------------------------------------- 1 | import { Component } from '@angular/core'; 2 | 3 | @Component({ 4 | selector: 'app-root', 5 | templateUrl: './app.component.html', 6 | styleUrls: ['./app.component.scss'] 7 | }) 8 | export class AppComponent { 9 | title = 'Sample frontend'; 10 | } 11 | -------------------------------------------------------------------------------- /src/FrontEnd/src/app/app.module.ts: -------------------------------------------------------------------------------- 1 | import { HttpClientModule } from '@angular/common/http'; 2 | import { APP_INITIALIZER, NgModule } from '@angular/core'; 3 | import { FormsModule, ReactiveFormsModule } from '@angular/forms'; 4 | import { BrowserModule } from '@angular/platform-browser'; 5 | import { AppRoutingModule } from './app-routing.module'; 6 | import { AppComponent } from './app.component'; 7 | import { OutsideRouterService } from './outsideRouter.service'; 8 | import { ProductModule } from './product/product.module'; 9 | 10 | @NgModule({ 11 | declarations: [AppComponent], 12 | imports: [ 13 | BrowserModule, 14 | HttpClientModule, 15 | FormsModule, 16 | ReactiveFormsModule, 17 | ProductModule, 18 | AppRoutingModule 19 | ], 20 | providers: [ 21 | { 22 | provide: APP_INITIALIZER, 23 | useFactory: initializeApp, 24 | deps: [OutsideRouterService], 25 | multi: true 26 | } 27 | ], 28 | bootstrap: [AppComponent] 29 | }) 30 | export class AppModule {} 31 | 32 | export function initializeApp(outsideRouter: OutsideRouterService) { 33 | return () => outsideRouter.setup(); 34 | } 35 | -------------------------------------------------------------------------------- /src/FrontEnd/src/app/outsideRouter.service.ts: -------------------------------------------------------------------------------- 1 | import { Injectable, Injector, NgZone } from '@angular/core'; 2 | import { Router } from '@angular/router'; 3 | 4 | /** 5 | * Service that allows Angular components to navigate from outside 6 | * Usage: 7 | * window.ngNavigate('route') 8 | */ 9 | @Injectable({ 10 | providedIn: 'root' 11 | }) 12 | export class OutsideRouterService { 13 | constructor(private zone: NgZone, private injector: Injector) {} 14 | 15 | public setup() { 16 | if ((window as any).ngNavigate) return; 17 | (window as any).ngNavigate = async (route: string) => { 18 | await this.zone.run(async () => { 19 | const router = this.injector.get(Router); 20 | await router.navigateByUrl(route); 21 | }); 22 | }; 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /src/FrontEnd/src/app/product/product-create.component.html: -------------------------------------------------------------------------------- 1 |

Create product

2 |
3 |
4 |

5 | Name: 7 |

8 |

9 | Price: 11 |

12 | 15 |
16 |
17 | -------------------------------------------------------------------------------- /src/FrontEnd/src/app/product/product-create.component.scss: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/giggio-samples/aspnetcore-tests-sample/ca06516470e5105e5aa6b5c73ffaeff58598abf3/src/FrontEnd/src/app/product/product-create.component.scss -------------------------------------------------------------------------------- /src/FrontEnd/src/app/product/product-create.component.spec.ts: -------------------------------------------------------------------------------- 1 | import { async, ComponentFixture, TestBed } from '@angular/core/testing'; 2 | import { ProductCreateComponent } from './product-create.component'; 3 | 4 | describe('ProductCreateComponent', () => { 5 | let component: ProductCreateComponent; 6 | let fixture: ComponentFixture; 7 | 8 | beforeEach(async(() => { 9 | TestBed.configureTestingModule({ 10 | declarations: [ProductCreateComponent] 11 | }).compileComponents(); 12 | })); 13 | 14 | beforeEach(() => { 15 | fixture = TestBed.createComponent(ProductCreateComponent); 16 | component = fixture.componentInstance; 17 | fixture.detectChanges(); 18 | }); 19 | 20 | it('should create', () => { 21 | expect(component).toBeTruthy(); 22 | }); 23 | }); 24 | -------------------------------------------------------------------------------- /src/FrontEnd/src/app/product/product-create.component.ts: -------------------------------------------------------------------------------- 1 | import { HttpClient } from '@angular/common/http'; 2 | import { Component, OnInit } from '@angular/core'; 3 | import { FormControl } from '@angular/forms'; 4 | import { Router } from '@angular/router'; 5 | import { Product } from './product'; 6 | 7 | @Component({ 8 | selector: 'app-product-create', 9 | templateUrl: './product-create.component.html', 10 | styleUrls: ['./product-create.component.scss'] 11 | }) 12 | export class ProductCreateComponent implements OnInit { 13 | public name = new FormControl(''); 14 | public price = new FormControl(''); 15 | protected url = 'http://localhost:5000/api/products'; 16 | constructor(protected httpClient: HttpClient, private router: Router) {} 17 | 18 | ngOnInit() {} 19 | 20 | create() { 21 | const product: Product = { 22 | name: this.name.value, 23 | price: this.price.value 24 | }; 25 | this.httpClient 26 | .post(`${this.url}`, product) 27 | .subscribe( 28 | () => this.router.navigate(['/product']), 29 | error => alert('Error adding product: ' + JSON.stringify(error)) 30 | ); 31 | } 32 | } 33 | -------------------------------------------------------------------------------- /src/FrontEnd/src/app/product/product-routing.module.ts: -------------------------------------------------------------------------------- 1 | import { NgModule } from '@angular/core'; 2 | import { RouterModule, Routes } from '@angular/router'; 3 | import { ProductCreateComponent } from './product-create.component'; 4 | import { ProductComponent } from './product.component'; 5 | 6 | const routes: Routes = [ 7 | { path: 'product/create', component: ProductCreateComponent }, 8 | { path: 'product', component: ProductComponent } 9 | ]; 10 | 11 | @NgModule({ 12 | imports: [RouterModule.forChild(routes)], 13 | exports: [RouterModule] 14 | }) 15 | export class ProductRoutingModule {} 16 | -------------------------------------------------------------------------------- /src/FrontEnd/src/app/product/product.component.html: -------------------------------------------------------------------------------- 1 |

Products:

2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 |
IdNamePrice
{{product.id}}{{product.name}}{{product.price}}
18 | New 19 | -------------------------------------------------------------------------------- /src/FrontEnd/src/app/product/product.component.scss: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/giggio-samples/aspnetcore-tests-sample/ca06516470e5105e5aa6b5c73ffaeff58598abf3/src/FrontEnd/src/app/product/product.component.scss -------------------------------------------------------------------------------- /src/FrontEnd/src/app/product/product.component.spec.ts: -------------------------------------------------------------------------------- 1 | import { async, ComponentFixture, TestBed } from '@angular/core/testing'; 2 | import { ProductComponent } from './product.component'; 3 | 4 | describe('ProductComponent', () => { 5 | let component: ProductComponent; 6 | let fixture: ComponentFixture; 7 | 8 | beforeEach(async(() => { 9 | TestBed.configureTestingModule({ 10 | declarations: [ProductComponent] 11 | }).compileComponents(); 12 | })); 13 | 14 | beforeEach(() => { 15 | fixture = TestBed.createComponent(ProductComponent); 16 | component = fixture.componentInstance; 17 | fixture.detectChanges(); 18 | }); 19 | 20 | it('should create', () => { 21 | expect(component).toBeTruthy(); 22 | }); 23 | }); 24 | -------------------------------------------------------------------------------- /src/FrontEnd/src/app/product/product.component.ts: -------------------------------------------------------------------------------- 1 | import { HttpClient } from '@angular/common/http'; 2 | import { Component, OnInit } from '@angular/core'; 3 | import { Product } from './product'; 4 | 5 | @Component({ 6 | selector: 'app-product', 7 | templateUrl: './product.component.html', 8 | styleUrls: ['./product.component.scss'] 9 | }) 10 | export class ProductComponent implements OnInit { 11 | protected url = 'http://localhost:5000/api/products'; 12 | public products: Product[] = []; 13 | constructor(protected httpClient: HttpClient) {} 14 | 15 | ngOnInit() { 16 | this.httpClient 17 | .get(this.url) 18 | .subscribe(products => (this.products = products)); 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /src/FrontEnd/src/app/product/product.module.ts: -------------------------------------------------------------------------------- 1 | import { CommonModule } from '@angular/common'; 2 | import { NgModule } from '@angular/core'; 3 | import { FormsModule, ReactiveFormsModule } from '@angular/forms'; 4 | import { ProductCreateComponent } from './product-create.component'; 5 | import { ProductRoutingModule } from './product-routing.module'; 6 | import { ProductComponent } from './product.component'; 7 | 8 | @NgModule({ 9 | imports: [ 10 | FormsModule, 11 | ReactiveFormsModule, 12 | ProductRoutingModule, 13 | CommonModule 14 | ], 15 | declarations: [ProductComponent, ProductCreateComponent], 16 | providers: [] 17 | }) 18 | export class ProductModule {} 19 | -------------------------------------------------------------------------------- /src/FrontEnd/src/app/product/product.ts: -------------------------------------------------------------------------------- 1 | export interface Product { 2 | id?: number; 3 | name: string; 4 | price: number; 5 | } 6 | -------------------------------------------------------------------------------- /src/FrontEnd/src/assets/.gitkeep: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/giggio-samples/aspnetcore-tests-sample/ca06516470e5105e5aa6b5c73ffaeff58598abf3/src/FrontEnd/src/assets/.gitkeep -------------------------------------------------------------------------------- /src/FrontEnd/src/browserslist: -------------------------------------------------------------------------------- 1 | # This file is currently used by autoprefixer to adjust CSS to support the below specified browsers 2 | # For additional information regarding the format and rule options, please see: 3 | # https://github.com/browserslist/browserslist#queries 4 | # 5 | # For IE 9-11 support, please remove 'not' from the last line of the file and adjust as needed 6 | 7 | > 0.5% 8 | last 2 versions 9 | Firefox ESR 10 | not dead 11 | not IE 9-11 -------------------------------------------------------------------------------- /src/FrontEnd/src/environments/environment.prod.ts: -------------------------------------------------------------------------------- 1 | export const environment = { 2 | production: true 3 | }; 4 | -------------------------------------------------------------------------------- /src/FrontEnd/src/environments/environment.ts: -------------------------------------------------------------------------------- 1 | // This file can be replaced during build by using the `fileReplacements` array. 2 | // `ng build --prod` replaces `environment.ts` with `environment.prod.ts`. 3 | // The list of file replacements can be found in `angular.json`. 4 | 5 | export const environment = { 6 | production: false 7 | }; 8 | 9 | /* 10 | * For easier debugging in development mode, you can import the following file 11 | * to ignore zone related error stack frames such as `zone.run`, `zoneDelegate.invokeTask`. 12 | * 13 | * This import should be commented out in production mode because it will have a negative impact 14 | * on performance if an error is thrown. 15 | */ 16 | // import 'zone.js/dist/zone-error'; // Included with Angular CLI. 17 | -------------------------------------------------------------------------------- /src/FrontEnd/src/favicon.ico: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/giggio-samples/aspnetcore-tests-sample/ca06516470e5105e5aa6b5c73ffaeff58598abf3/src/FrontEnd/src/favicon.ico -------------------------------------------------------------------------------- /src/FrontEnd/src/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | FrontEnd 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | -------------------------------------------------------------------------------- /src/FrontEnd/src/karma.conf.js: -------------------------------------------------------------------------------- 1 | // Karma configuration file, see link for more information 2 | // https://karma-runner.github.io/1.0/config/configuration-file.html 3 | 4 | module.exports = function (config) { 5 | config.set({ 6 | basePath: '', 7 | frameworks: ['jasmine', '@angular-devkit/build-angular'], 8 | plugins: [ 9 | require('karma-jasmine'), 10 | require('karma-chrome-launcher'), 11 | require('karma-jasmine-html-reporter'), 12 | require('karma-coverage-istanbul-reporter'), 13 | require('@angular-devkit/build-angular/plugins/karma') 14 | ], 15 | client: { 16 | clearContext: false // leave Jasmine Spec Runner output visible in browser 17 | }, 18 | coverageIstanbulReporter: { 19 | dir: require('path').join(__dirname, '../coverage/FrontEnd'), 20 | reports: ['html', 'lcovonly', 'text-summary'], 21 | fixWebpackSourcePaths: true 22 | }, 23 | reporters: ['progress', 'kjhtml'], 24 | port: 9876, 25 | colors: true, 26 | logLevel: config.LOG_INFO, 27 | autoWatch: true, 28 | browsers: ['Chrome'], 29 | singleRun: false, 30 | restartOnFileChange: true 31 | }); 32 | }; 33 | -------------------------------------------------------------------------------- /src/FrontEnd/src/main.ts: -------------------------------------------------------------------------------- 1 | import { enableProdMode } from '@angular/core'; 2 | import { platformBrowserDynamic } from '@angular/platform-browser-dynamic'; 3 | 4 | import { AppModule } from './app/app.module'; 5 | import { environment } from './environments/environment'; 6 | 7 | if (environment.production) { 8 | enableProdMode(); 9 | } 10 | 11 | platformBrowserDynamic().bootstrapModule(AppModule) 12 | .catch(err => console.error(err)); 13 | -------------------------------------------------------------------------------- /src/FrontEnd/src/polyfills.ts: -------------------------------------------------------------------------------- 1 | /** 2 | * This file includes polyfills needed by Angular and is loaded before the app. 3 | * You can add your own extra polyfills to this file. 4 | * 5 | * This file is divided into 2 sections: 6 | * 1. Browser polyfills. These are applied before loading ZoneJS and are sorted by browsers. 7 | * 2. Application imports. Files imported after ZoneJS that should be loaded before your main 8 | * file. 9 | * 10 | * The current setup is for so-called "evergreen" browsers; the last versions of browsers that 11 | * automatically update themselves. This includes Safari >= 10, Chrome >= 55 (including Opera), 12 | * Edge >= 13 on the desktop, and iOS 10 and Chrome on mobile. 13 | * 14 | * Learn more in https://angular.io/guide/browser-support 15 | */ 16 | 17 | /*************************************************************************************************** 18 | * BROWSER POLYFILLS 19 | */ 20 | 21 | /** IE10 and IE11 requires the following for NgClass support on SVG elements */ 22 | // import 'classlist.js'; // Run `npm install --save classlist.js`. 23 | 24 | /** 25 | * Web Animations `@angular/platform-browser/animations` 26 | * Only required if AnimationBuilder is used within the application and using IE/Edge or Safari. 27 | * Standard animation support in Angular DOES NOT require any polyfills (as of Angular 6.0). 28 | */ 29 | // import 'web-animations-js'; // Run `npm install --save web-animations-js`. 30 | 31 | /** 32 | * By default, zone.js will patch all possible macroTask and DomEvents 33 | * user can disable parts of macroTask/DomEvents patch by setting following flags 34 | * because those flags need to be set before `zone.js` being loaded, and webpack 35 | * will put import in the top of bundle, so user need to create a separate file 36 | * in this directory (for example: zone-flags.ts), and put the following flags 37 | * into that file, and then add the following code before importing zone.js. 38 | * import './zone-flags.ts'; 39 | * 40 | * The flags allowed in zone-flags.ts are listed here. 41 | * 42 | * The following flags will work for all browsers. 43 | * 44 | * (window as any).__Zone_disable_requestAnimationFrame = true; // disable patch requestAnimationFrame 45 | * (window as any).__Zone_disable_on_property = true; // disable patch onProperty such as onclick 46 | * (window as any).__zone_symbol__BLACK_LISTED_EVENTS = ['scroll', 'mousemove']; // disable patch specified eventNames 47 | * 48 | * in IE/Edge developer tools, the addEventListener will also be wrapped by zone.js 49 | * with the following flag, it will bypass `zone.js` patch for IE/Edge 50 | * 51 | * (window as any).__Zone_enable_cross_context_check = true; 52 | * 53 | */ 54 | 55 | /*************************************************************************************************** 56 | * Zone JS is required by default for Angular itself. 57 | */ 58 | import 'zone.js/dist/zone'; // Included with Angular CLI. 59 | 60 | 61 | /*************************************************************************************************** 62 | * APPLICATION IMPORTS 63 | */ 64 | -------------------------------------------------------------------------------- /src/FrontEnd/src/styles.scss: -------------------------------------------------------------------------------- 1 | /* You can add global styles to this file, and also import other style files */ 2 | -------------------------------------------------------------------------------- /src/FrontEnd/src/test.ts: -------------------------------------------------------------------------------- 1 | // This file is required by karma.conf.js and loads recursively all the .spec and framework files 2 | 3 | import 'zone.js/dist/zone-testing'; 4 | import { getTestBed } from '@angular/core/testing'; 5 | import { 6 | BrowserDynamicTestingModule, 7 | platformBrowserDynamicTesting 8 | } from '@angular/platform-browser-dynamic/testing'; 9 | 10 | declare const require: any; 11 | 12 | // First, initialize the Angular testing environment. 13 | getTestBed().initTestEnvironment( 14 | BrowserDynamicTestingModule, 15 | platformBrowserDynamicTesting() 16 | ); 17 | // Then we find all the tests. 18 | const context = require.context('./', true, /\.spec\.ts$/); 19 | // And load the modules. 20 | context.keys().map(context); 21 | -------------------------------------------------------------------------------- /src/FrontEnd/src/tsconfig.app.json: -------------------------------------------------------------------------------- 1 | { 2 | "extends": "../tsconfig.json", 3 | "compilerOptions": { 4 | "outDir": "../out-tsc/app", 5 | "types": [] 6 | }, 7 | "exclude": [ 8 | "test.ts", 9 | "**/*.spec.ts" 10 | ] 11 | } 12 | -------------------------------------------------------------------------------- /src/FrontEnd/src/tsconfig.spec.json: -------------------------------------------------------------------------------- 1 | { 2 | "extends": "../tsconfig.json", 3 | "compilerOptions": { 4 | "outDir": "../out-tsc/spec", 5 | "types": [ 6 | "jasmine", 7 | "node" 8 | ] 9 | }, 10 | "files": [ 11 | "test.ts", 12 | "polyfills.ts" 13 | ], 14 | "include": [ 15 | "**/*.spec.ts", 16 | "**/*.d.ts" 17 | ] 18 | } 19 | -------------------------------------------------------------------------------- /src/FrontEnd/src/tslint.json: -------------------------------------------------------------------------------- 1 | { 2 | "extends": "../tslint.json", 3 | "rules": { 4 | "directive-selector": [ 5 | true, 6 | "attribute", 7 | "app", 8 | "camelCase" 9 | ], 10 | "component-selector": [ 11 | true, 12 | "element", 13 | "app", 14 | "kebab-case" 15 | ] 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /src/FrontEnd/tsconfig.json: -------------------------------------------------------------------------------- 1 | { 2 | "compileOnSave": false, 3 | "compilerOptions": { 4 | "baseUrl": "./", 5 | "outDir": "./dist/out-tsc", 6 | "sourceMap": true, 7 | "declaration": false, 8 | "module": "es2015", 9 | "moduleResolution": "node", 10 | "emitDecoratorMetadata": true, 11 | "experimentalDecorators": true, 12 | "importHelpers": true, 13 | "target": "es5", 14 | "typeRoots": [ 15 | "node_modules/@types" 16 | ], 17 | "lib": [ 18 | "es2018", 19 | "dom" 20 | ] 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /src/FrontEnd/tslint.json: -------------------------------------------------------------------------------- 1 | { 2 | "extends": "tslint:recommended", 3 | "rulesDirectory": ["codelyzer"], 4 | "rules": { 5 | "array-type": false, 6 | "arrow-parens": false, 7 | "curly": [true, "as-needed"], 8 | "deprecation": { 9 | "severity": "warn" 10 | }, 11 | "import-blacklist": [true, "rxjs/Rx"], 12 | "interface-name": false, 13 | "max-classes-per-file": false, 14 | "max-line-length": [true, 140], 15 | "member-access": false, 16 | "member-ordering": [ 17 | true, 18 | { 19 | "order": [ 20 | "static-field", 21 | "instance-field", 22 | "static-method", 23 | "instance-method" 24 | ] 25 | } 26 | ], 27 | "no-consecutive-blank-lines": false, 28 | "no-console": [true, "debug", "info", "time", "timeEnd", "trace"], 29 | "no-empty": false, 30 | "no-inferrable-types": [true, "ignore-params"], 31 | "no-non-null-assertion": true, 32 | "no-redundant-jsdoc": true, 33 | "no-switch-case-fall-through": true, 34 | "no-use-before-declare": true, 35 | "no-var-requires": false, 36 | "object-literal-key-quotes": [true, "as-needed"], 37 | "object-literal-sort-keys": false, 38 | "ordered-imports": false, 39 | "quotemark": [true, "single"], 40 | "trailing-comma": false, 41 | "no-output-on-prefix": true, 42 | "use-input-property-decorator": true, 43 | "use-output-property-decorator": true, 44 | "use-host-property-decorator": true, 45 | "no-input-rename": true, 46 | "no-output-rename": true, 47 | "use-life-cycle-interface": true, 48 | "use-pipe-transform-interface": true, 49 | "component-class-suffix": true, 50 | "directive-class-suffix": true 51 | } 52 | } 53 | -------------------------------------------------------------------------------- /src/SampleApp/Controllers/ProductsController.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.AspNetCore.Mvc; 2 | using SampleApp.Models; 3 | using System.Collections.Generic; 4 | using System.Threading.Tasks; 5 | 6 | namespace SampleApp.Controllers 7 | { 8 | [Route("api/[controller]")] 9 | [ApiController] 10 | public class ProductsController : ControllerBase 11 | { 12 | private readonly IProductsRepository productsRepository; 13 | 14 | public ProductsController(IProductsRepository productsRepository) => this.productsRepository = productsRepository; 15 | 16 | // GET: api/Products 17 | [HttpGet] 18 | public async Task>> GetProduct() 19 | { 20 | var products = await productsRepository.GetAllAsync(); 21 | return Ok(products); 22 | } 23 | 24 | // GET: api/Products/5 25 | [HttpGet("{id}")] 26 | public async Task> GetProduct(int id) 27 | { 28 | var product = await productsRepository.GetAsync(id); 29 | if (product == null) 30 | return NotFound(); 31 | return product; 32 | } 33 | 34 | // PUT: api/Products/5 35 | [HttpPut("{id}")] 36 | public async Task PutProduct(int id, Product product) 37 | { 38 | if (id != product.Id) 39 | return BadRequest(); 40 | var success = await productsRepository.UpdateAsync(product); 41 | if (!success) 42 | return NotFound(); 43 | return NoContent(); 44 | } 45 | 46 | // POST: api/Products 47 | [HttpPost] 48 | public async Task> PostProduct(Product product) 49 | { 50 | if (product.Price <= 0) 51 | return BadRequest(); 52 | var success = await productsRepository.CreateAsync(product); 53 | if (success) 54 | return CreatedAtAction("GetProduct", new { id = product.Id }, product); 55 | return BadRequest(); 56 | } 57 | 58 | // DELETE: api/Products/5 59 | [HttpDelete("{id}")] 60 | public async Task DeleteProduct(int id) 61 | { 62 | var success = await productsRepository.DeleteAsync(id); 63 | if (!success) 64 | return NotFound(); 65 | return NoContent(); 66 | } 67 | } 68 | } 69 | -------------------------------------------------------------------------------- /src/SampleApp/Models/Product.cs: -------------------------------------------------------------------------------- 1 | namespace SampleApp.Models 2 | { 3 | public class Product 4 | { 5 | public int Id { get; set; } 6 | public string Name { get; set; } 7 | public decimal Price { get; set; } 8 | 9 | public bool IsExpensive => Price >= 1000; 10 | } 11 | } 12 | -------------------------------------------------------------------------------- /src/SampleApp/Models/ProductsRepository.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.EntityFrameworkCore; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Threading.Tasks; 5 | 6 | namespace SampleApp.Models 7 | { 8 | public interface IProductsRepository 9 | { 10 | Task> GetAllAsync(); 11 | Task GetAsync(int id); 12 | Task CreateAsync(Product product); 13 | Task UpdateAsync(Product product); 14 | Task ExistsAsync(int id); 15 | Task DeleteAsync(int id); 16 | } 17 | 18 | public class ProductsRepository : IProductsRepository 19 | { 20 | public ProductsRepository(SampleAppContext context) => this.context = context; 21 | 22 | private readonly SampleAppContext context; 23 | 24 | public async Task CreateAsync(Product product) 25 | { 26 | if (product == null) 27 | throw new System.ArgumentNullException(nameof(product)); 28 | await context.Product.AddAsync(product); 29 | await context.SaveChangesAsync(); 30 | return true; 31 | } 32 | 33 | public async Task GetAsync(int id) => await context.Product.FindAsync(id); 34 | 35 | public async Task> GetAllAsync() => await context.Product.ToListAsync(); 36 | 37 | public async Task UpdateAsync(Product product) 38 | { 39 | if (product == null) 40 | throw new System.ArgumentNullException(nameof(product)); 41 | if (product.Id <= 0) 42 | return false; 43 | context.Entry(product).State = EntityState.Modified; 44 | try 45 | { 46 | await context.SaveChangesAsync(); 47 | } 48 | catch (DbUpdateConcurrencyException) 49 | { 50 | return false; 51 | } 52 | return true; 53 | } 54 | 55 | public Task ExistsAsync(int id) => context.Product.AnyAsync(e => e.Id == id); 56 | 57 | public async Task DeleteAsync(int id) 58 | { 59 | var product = await GetAsync(id); 60 | if (product == null) 61 | return false; 62 | context.Product.Remove(product); 63 | await context.SaveChangesAsync(); 64 | return true; 65 | } 66 | } 67 | } 68 | -------------------------------------------------------------------------------- /src/SampleApp/Models/SampleAppContext.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.EntityFrameworkCore; 2 | 3 | namespace SampleApp.Models 4 | { 5 | public class SampleAppContext : DbContext 6 | { 7 | public SampleAppContext(DbContextOptions options) 8 | : base(options) 9 | { 10 | } 11 | 12 | public DbSet Product { get; set; } 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /src/SampleApp/Program.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.AspNetCore; 2 | using Microsoft.AspNetCore.Hosting; 3 | using Microsoft.Extensions.DependencyInjection; 4 | using Microsoft.Extensions.Logging; 5 | using SampleApp.Models; 6 | 7 | namespace SampleApp 8 | { 9 | public class Program 10 | { 11 | public static void Main(string[] args) 12 | { 13 | var host = CreateWebHostBuilder(args).Build(); 14 | var env = host.Services.GetRequiredService(); 15 | if (env.IsDevelopment()) 16 | { 17 | using (var scope = host.Services.CreateScope()) 18 | { 19 | var scopedServices = scope.ServiceProvider; 20 | var db = scopedServices.GetRequiredService(); 21 | var logger = scopedServices.GetRequiredService>(); 22 | db.Database.EnsureCreated(); 23 | } 24 | } 25 | host.Run(); 26 | } 27 | 28 | public static IWebHostBuilder CreateWebHostBuilder(string[] args) => 29 | WebHost.CreateDefaultBuilder(args) 30 | .UseStartup(); 31 | } 32 | } 33 | -------------------------------------------------------------------------------- /src/SampleApp/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:4972", 8 | "sslPort": 44342 9 | } 10 | }, 11 | "profiles": { 12 | "IIS Express": { 13 | "commandName": "IISExpress", 14 | "launchBrowser": true, 15 | "launchUrl": "api/products", 16 | "environmentVariables": { 17 | "ASPNETCORE_ENVIRONMENT": "Development" 18 | } 19 | }, 20 | "SampleApp": { 21 | "commandName": "Project", 22 | "launchBrowser": true, 23 | "launchUrl": "api/products", 24 | "applicationUrl": "https://localhost:5001;http://localhost:5000", 25 | "environmentVariables": { 26 | "ASPNETCORE_ENVIRONMENT": "Development" 27 | } 28 | } 29 | } 30 | } -------------------------------------------------------------------------------- /src/SampleApp/SampleApp.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | netcoreapp2.2 5 | InProcess 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | -------------------------------------------------------------------------------- /src/SampleApp/Startup.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Threading.Tasks; 5 | using Microsoft.AspNetCore.Builder; 6 | using Microsoft.AspNetCore.Hosting; 7 | using Microsoft.AspNetCore.HttpsPolicy; 8 | using Microsoft.AspNetCore.Mvc; 9 | using Microsoft.Extensions.Configuration; 10 | using Microsoft.Extensions.DependencyInjection; 11 | using Microsoft.Extensions.Logging; 12 | using Microsoft.Extensions.Options; 13 | using SampleApp.Models; 14 | using Microsoft.EntityFrameworkCore; 15 | 16 | namespace SampleApp 17 | { 18 | public class Startup 19 | { 20 | private readonly IHostingEnvironment env; 21 | 22 | public Startup(IConfiguration configuration, IHostingEnvironment env) 23 | { 24 | Configuration = configuration; 25 | this.env = env; 26 | } 27 | 28 | public IConfiguration Configuration { get; } 29 | 30 | public void ConfigureServices(IServiceCollection services) 31 | { 32 | services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2); 33 | services.AddScoped(); 34 | if (env.IsEnvironment("Test")) 35 | { 36 | services.AddEntityFrameworkInMemoryDatabase(); 37 | services.AddDbContext(options => options.UseInMemoryDatabase("InMemoryDbForTesting")); 38 | } 39 | else 40 | { 41 | services.AddDbContext(options => options.UseSqlServer(Configuration.GetConnectionString("SampleAppContext"))); 42 | } 43 | services.AddCors(options => 44 | { 45 | options.AddPolicy("cors", builder => 46 | { 47 | builder.WithOrigins("http://localhost:4200", "http://localhost:7200").AllowAnyHeader().AllowAnyMethod(); 48 | }); 49 | }); 50 | } 51 | 52 | 53 | public void Configure(IApplicationBuilder app) 54 | { 55 | if (env.IsDevelopment()) 56 | { 57 | app.UseDeveloperExceptionPage(); 58 | } 59 | else if (env.IsEnvironment("Test")) 60 | { 61 | } 62 | else 63 | { 64 | app.UseHsts(); 65 | app.UseHttpsRedirection(); 66 | } 67 | app.UseCors("cors"); 68 | app.UseMvc(); 69 | } 70 | } 71 | } 72 | -------------------------------------------------------------------------------- /src/SampleApp/appsettings.Development.json: -------------------------------------------------------------------------------- 1 | { 2 | "Logging": { 3 | "LogLevel": { 4 | "Default": "Debug", 5 | "System": "Information", 6 | "Microsoft": "Information" 7 | } 8 | }, 9 | "ConnectionStrings": { 10 | "SampleAppContext": "Server=(localdb)\\mssqllocaldb;Database=SampleAppContext;Trusted_Connection=True;MultipleActiveResultSets=true" 11 | } 12 | } 13 | -------------------------------------------------------------------------------- /src/SampleApp/appsettings.Test.json: -------------------------------------------------------------------------------- 1 | { 2 | "Logging": { 3 | "LogLevel": { 4 | "Default": "Debug", 5 | "System": "Information", 6 | "Microsoft": "Information" 7 | } 8 | } 9 | } 10 | -------------------------------------------------------------------------------- /src/SampleApp/appsettings.json: -------------------------------------------------------------------------------- 1 | { 2 | "Logging": { 3 | "LogLevel": { 4 | "Default": "Warning" 5 | } 6 | }, 7 | "AllowedHosts": "*" 8 | } -------------------------------------------------------------------------------- /test/AcceptanceTests/AcceptanceTests.csproj: -------------------------------------------------------------------------------- 1 |  2 | 3 | netcoreapp2.2 4 | false 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | -------------------------------------------------------------------------------- /test/AcceptanceTests/BaseAcceptanceTest.cs: -------------------------------------------------------------------------------- 1 | using AcceptanceTests.Pages; 2 | using Lambda3.AspNetCore.Mvc.Testing; 3 | using Microsoft.Extensions.DependencyInjection; 4 | using NUnit.Framework; 5 | using SampleApp; 6 | using System; 7 | using System.Net.Http; 8 | 9 | namespace AcceptanceTests 10 | { 11 | public class BaseAcceptanceTest 12 | { 13 | public static WebApplicationFactory WebAppFactory { get; set; } 14 | } 15 | 16 | public abstract class BaseAcceptanceTest 17 | where TPage : Page, new() 18 | { 19 | private IServiceScope scope; 20 | protected IServiceProvider serviceProvider; 21 | protected HttpClient client; 22 | 23 | public TPage Page { get; protected set; } = new TPage(); 24 | 25 | [OneTimeSetUp] 26 | public void BaseOneTimeSetUp() 27 | { 28 | client = BaseAcceptanceTest.WebAppFactory.CreateClient(); 29 | scope = BaseAcceptanceTest.WebAppFactory.Host.Services.CreateScope(); 30 | serviceProvider = scope.ServiceProvider; 31 | } 32 | 33 | [OneTimeTearDown] 34 | public void BaseOneTimeTearDown() 35 | { 36 | scope?.Dispose(); 37 | client?.Dispose(); 38 | } 39 | } 40 | } 41 | -------------------------------------------------------------------------------- /test/AcceptanceTests/DriverManager.cs: -------------------------------------------------------------------------------- 1 | using OpenQA.Selenium; 2 | using OpenQA.Selenium.Chrome; 3 | using System; 4 | using System.Diagnostics; 5 | using System.Runtime.InteropServices; 6 | 7 | namespace AcceptanceTests 8 | { 9 | public static class DriverManager 10 | { 11 | public static IWebDriver Driver { get; private set; } 12 | 13 | public static void Start() 14 | { 15 | var chromeOptions = new ChromeOptions(); 16 | chromeOptions.AddArgument("--start-maximized"); 17 | if (!Debugger.IsAttached) 18 | { 19 | chromeOptions.AddArgument("--headless"); 20 | chromeOptions.AddArgument("--window-size=1920,1080"); 21 | if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) 22 | chromeOptions.AddArgument("--disable-gpu"); // until not needed, see https://bugs.chromium.org/p/chromium/issues/detail?id=737678 23 | } 24 | Driver = new ChromeDriver(Environment.CurrentDirectory, chromeOptions, TimeSpan.FromSeconds(120)); 25 | Driver.Manage().Window.Maximize(); 26 | } 27 | 28 | public static void Stop() => Driver?.Quit(); 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /test/AcceptanceTests/FrontendServer.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Diagnostics; 3 | 4 | namespace AcceptanceTests 5 | { 6 | public class FrontendServer : IDisposable 7 | { 8 | private readonly string projectDir; 9 | private Process process; 10 | 11 | public FrontendServer(string projectDir) => this.projectDir = projectDir; 12 | 13 | public string BaseUrl { get; } = "http://localhost:7200"; 14 | 15 | public void Dispose() 16 | { 17 | if (process == null) 18 | return; 19 | if (!process.HasExited) 20 | KillWindowsProcess(process.Id); 21 | process.Dispose(); 22 | process = null; 23 | } 24 | 25 | public void StartFrontEnd() => process = Process.Start(new ProcessStartInfo("npm", "run start:test") { UseShellExecute = true, WorkingDirectory = projectDir }); 26 | 27 | private void KillWindowsProcess(int processId) // todo: multi platform 28 | { 29 | using (var killer = Process.Start(new ProcessStartInfo("taskkill.exe", $"/PID {processId} /T /F") { UseShellExecute = false })) 30 | killer.WaitForExit(2000); 31 | } 32 | 33 | } 34 | } -------------------------------------------------------------------------------- /test/AcceptanceTests/Pages/HomePage.cs: -------------------------------------------------------------------------------- 1 | using OpenQA.Selenium; 2 | 3 | namespace AcceptanceTests.Pages 4 | { 5 | public class HomePage : Page 6 | { 7 | public override string Path => "/"; 8 | 9 | public bool HasTitle() => Driver.FindElement(By.Id("title")).Displayed; 10 | } 11 | } 12 | -------------------------------------------------------------------------------- /test/AcceptanceTests/Pages/Page.cs: -------------------------------------------------------------------------------- 1 | using System.Linq; 2 | using System.Reflection; 3 | using OpenQA.Selenium; 4 | using System; 5 | 6 | namespace AcceptanceTests.Pages 7 | { 8 | public abstract class Page 9 | { 10 | public static string BaseUrl { get; set; } 11 | 12 | public abstract string Path { get; } 13 | 14 | public string CurrentUrl => Driver.Url; 15 | 16 | public virtual void Navigate() 17 | { 18 | Driver.Url = $"{BaseUrl}{Path}"; 19 | Driver.Navigate(); 20 | } 21 | 22 | public virtual void NgNavigate(params object[] pathParts) 23 | { 24 | if (pathParts == null) 25 | throw new ArgumentNullException(nameof(pathParts)); 26 | NgNavigateAbsolute(string.Format(Path, pathParts)); 27 | } 28 | 29 | public virtual void NgNavigateAbsolute(string path) 30 | { 31 | if (string.IsNullOrWhiteSpace(path)) 32 | throw new ArgumentException("Path is required.", nameof(path)); 33 | JsDriver.ExecuteAsyncScript($"var callback = arguments[arguments.length - 1];ngNavigate('/').then(function () {{ return ngNavigate('{path}'); }}).then(callback, callback);"); 34 | Wait(); 35 | } 36 | 37 | protected static IWebDriver Driver => DriverManager.Driver; 38 | 39 | protected static IJavaScriptExecutor JsDriver => Driver as IJavaScriptExecutor; 40 | 41 | public IWebDriver Type(object model) 42 | { 43 | var modelType = model.GetType(); 44 | var props = modelType.GetProperties(BindingFlags.Public | BindingFlags.Instance); 45 | foreach (var prop in props) 46 | Type(By.Id(prop.Name.ToLower()), prop.GetValue(model).ToString()); 47 | return Driver; 48 | } 49 | 50 | protected IWebElement Type(By by, string text) 51 | { 52 | var element = Driver.WaitUntil(x => 53 | { 54 | var els = x.FindElements(by); 55 | if (els.Count == 0) 56 | return null; 57 | var el = els.First(); 58 | return el.Displayed && el.Enabled ? el : null; 59 | }); 60 | element.Clear(); 61 | element.SendKeys(text); 62 | return element; 63 | } 64 | 65 | public void Wait() => Driver.WaitUntil(driver => driver.FindElement(By.TagName("app-root")).FindElements(By.XPath(".//*")).Any()); 66 | } 67 | } 68 | -------------------------------------------------------------------------------- /test/AcceptanceTests/Pages/ProductCreatePage.cs: -------------------------------------------------------------------------------- 1 | using OpenQA.Selenium; 2 | 3 | namespace AcceptanceTests.Pages 4 | { 5 | public class ProductCreatePage : Page 6 | { 7 | public override string Path => "/product/create"; 8 | 9 | public void Submit() => Driver.WaitElementEnabled(By.Id("productCreate")).Click(); 10 | } 11 | } 12 | -------------------------------------------------------------------------------- /test/AcceptanceTests/ProjectFinder.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.IO; 3 | using System.Linq; 4 | using System.Reflection; 5 | 6 | namespace AcceptanceTests 7 | { 8 | public class ProjectFinder 9 | { 10 | public static string FindProjectDir(string projectPath) 11 | { 12 | var callingAssemblyDirectory = Directory.GetParent(new Uri(Assembly.GetCallingAssembly().CodeBase).LocalPath).FullName; 13 | return FindSolutionRootPath(callingAssemblyDirectory, out var solutionRoot) 14 | ? Path.Combine(solutionRoot, projectPath) 15 | : null; 16 | 17 | } 18 | 19 | private static bool FindSolutionRootPath(string callingAssemblyDirectory, out string repositoryRoot) 20 | { 21 | var pathRoot = Path.GetPathRoot(callingAssemblyDirectory); 22 | var candidateDirectory = callingAssemblyDirectory; 23 | while (candidateDirectory != pathRoot) 24 | { 25 | if (Directory.EnumerateFiles(candidateDirectory, "*.sln").Any()) 26 | { 27 | repositoryRoot = candidateDirectory; 28 | return true; 29 | } 30 | candidateDirectory = Directory.GetParent(candidateDirectory).FullName; 31 | } 32 | repositoryRoot = null; 33 | return false; 34 | } 35 | 36 | } 37 | } -------------------------------------------------------------------------------- /test/AcceptanceTests/Setup.cs: -------------------------------------------------------------------------------- 1 | using AcceptanceTests.Pages; 2 | using Bogus; 3 | using IntegrationTests; 4 | using Lambda3.AspNetCore.Mvc.Testing; 5 | using NUnit.Framework; 6 | using SampleApp; 7 | using System; 8 | using System.Threading.Tasks; 9 | 10 | namespace AcceptanceTests 11 | { 12 | [SetUpFixture] 13 | public class Setup 14 | { 15 | private WebApplicationFactory webAppFactory; 16 | private FrontendServer frontendServer; 17 | 18 | [OneTimeSetUp] 19 | public async Task OneTimeSetUp() 20 | { 21 | StartApiServer(); 22 | StartFrontend(); 23 | DriverManager.Start(); 24 | await webAppFactory.MigrateDbAndSeedAsync(); 25 | BaseAcceptanceTest.WebAppFactory = webAppFactory; 26 | Page.BaseUrl = frontendServer.BaseUrl; 27 | NavigateHome(); 28 | } 29 | 30 | private void StartApiServer() => 31 | webAppFactory = new WebApplicationFactory(port: 5000).EnsureServerStarted(); 32 | 33 | private void StartFrontend() 34 | { 35 | frontendServer = new FrontendServer(ProjectFinder.FindProjectDir("src/FrontEnd")); 36 | frontendServer.StartFrontEnd(); 37 | } 38 | 39 | private void NavigateHome() 40 | { 41 | try 42 | { 43 | new HomePage().Navigate(); 44 | } 45 | catch (Exception ex) 46 | { 47 | throw new Exception("Could not navigate home during test setup.", ex); 48 | } 49 | } 50 | 51 | [OneTimeTearDown] 52 | public void OneTimeTearDown() 53 | { 54 | RunAndSwallowException(() => DriverManager.Stop()); 55 | RunAndSwallowException(() => frontendServer?.Dispose()); 56 | RunAndSwallowException(() => webAppFactory?.Dispose()); 57 | } 58 | 59 | private static void RunAndSwallowException(Action a) 60 | { 61 | try 62 | { 63 | a(); 64 | } 65 | catch { } 66 | } 67 | } 68 | } 69 | -------------------------------------------------------------------------------- /test/AcceptanceTests/Tests/ProductTests.cs: -------------------------------------------------------------------------------- 1 | using AcceptanceTests.Pages; 2 | using FluentAssertions; 3 | using Microsoft.Extensions.DependencyInjection; 4 | using NUnit.Framework; 5 | using SampleApp.Models; 6 | using System.Linq; 7 | using System.Threading.Tasks; 8 | 9 | namespace AcceptanceTests.Tests 10 | { 11 | public class ProductCreateTest : BaseAcceptanceTest 12 | { 13 | private IProductsRepository repository; 14 | 15 | [OneTimeSetUp] 16 | public async Task CreateProduct() 17 | { 18 | repository = serviceProvider.GetService(); 19 | var allProducts = await repository.GetAllAsync(); 20 | foreach (var product in allProducts) 21 | await repository.DeleteAsync(product.Id); 22 | Page.NgNavigate(); 23 | Page.Type(new { name = "Foo", price = "23" }); 24 | Page.Submit(); 25 | System.Threading.Thread.Sleep(5000); // todo: use a clever wait to wait for Angular 26 | } 27 | 28 | [Test] 29 | public void UrlIsCorrect() => Page.CurrentUrl.Should().Be("http://localhost:7200/product"); 30 | 31 | 32 | [Test] 33 | public async Task ProductCreatedOnDb() 34 | { 35 | var product = (await repository.GetAllAsync()).First(); 36 | product.Name.Should().Be("Foo"); 37 | } 38 | 39 | [Test] 40 | public async Task ThereIsOnlyOneProductAfterCreating() => (await repository.GetAllAsync()).Count().Should().Be(1); 41 | } 42 | } 43 | -------------------------------------------------------------------------------- /test/AcceptanceTests/Tests/SmokeTest.cs: -------------------------------------------------------------------------------- 1 | using AcceptanceTests.Pages; 2 | using FluentAssertions; 3 | using NUnit.Framework; 4 | using OpenQA.Selenium; 5 | 6 | namespace AcceptanceTests.Tests 7 | { 8 | public class SmokeTest : BaseAcceptanceTest 9 | { 10 | [Test] 11 | public void HomeWithoutPageObject() // don't do this 12 | { 13 | (DriverManager.Driver as IJavaScriptExecutor).ExecuteAsyncScript("var callback = arguments[arguments.length - 1];ngNavigate('/').then(function () { return ngNavigate('/'); }).then(callback, callback);"); 14 | DriverManager.Driver.FindElement(By.Id("title")).Displayed.Should().BeTrue(); 15 | } 16 | 17 | [Test] 18 | public void Home() 19 | { 20 | var homePage = new HomePage(); 21 | homePage.NgNavigate(); 22 | homePage.HasTitle().Should().BeTrue(); 23 | } 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /test/AcceptanceTests/WaitElementExtension.cs: -------------------------------------------------------------------------------- 1 | using OpenQA.Selenium; 2 | using OpenQA.Selenium.Support.UI; 3 | using System; 4 | 5 | namespace AcceptanceTests 6 | { 7 | public static class WaitElementExtension 8 | { 9 | public static readonly TimeSpan DefaultTimeout = TimeSpan.FromSeconds(20); 10 | 11 | public static IWebElement WaitElementEnabled(this IWebDriver driver, By by, int? waitInSeconds = null) => 12 | new WebDriverWait(driver, GetTimeout(waitInSeconds)).Until(x => 13 | { 14 | try 15 | { 16 | var element = x.FindElement(by); 17 | return element?.Enabled == true ? element : null; 18 | } 19 | catch (StaleElementReferenceException) 20 | { 21 | return null; 22 | } 23 | catch (NoSuchElementException) 24 | { 25 | return null; 26 | } 27 | }); 28 | 29 | 30 | public static TResult WaitUntil(this IWebDriver driver, Func condition, int? waitInSeconds = null) 31 | { 32 | if (condition == null) 33 | throw new ArgumentNullException(nameof(condition)); 34 | return new WebDriverWait(driver, GetTimeout(waitInSeconds)).Until(d => 35 | { 36 | try 37 | { 38 | return condition.Invoke(d); 39 | } 40 | catch (StaleElementReferenceException) 41 | { 42 | return default; 43 | } 44 | }); 45 | } 46 | 47 | public static TimeSpan GetTimeout(int? seconds) => 48 | seconds != null ? TimeSpan.FromSeconds(seconds.Value) : DefaultTimeout; 49 | } 50 | } 51 | -------------------------------------------------------------------------------- /test/IntegrationTests/BaseIntegrationTest.cs: -------------------------------------------------------------------------------- 1 | using Lambda3.AspNetCore.Mvc.Testing; 2 | using Microsoft.Extensions.DependencyInjection; 3 | using NUnit.Framework; 4 | using SampleApp; 5 | using System; 6 | using System.Net.Http; 7 | 8 | namespace IntegrationTests 9 | { 10 | public abstract class BaseIntegrationTest 11 | { 12 | private IServiceScope scope; 13 | protected IServiceProvider serviceProvider; 14 | protected HttpClient client; 15 | 16 | public static WebApplicationFactory WebAppFactory { get; set; } 17 | 18 | [OneTimeSetUp] 19 | public void BaseIntegrationTestOneTimeSetUp() 20 | { 21 | client = WebAppFactory.CreateDefaultClient(); 22 | scope = WebAppFactory.Host.Services.CreateScope(); 23 | serviceProvider = scope.ServiceProvider; 24 | } 25 | 26 | [OneTimeTearDown] 27 | public void BaseIntegrationTestOneTimeTearDown() => scope.Dispose(); 28 | } 29 | } 30 | 31 | -------------------------------------------------------------------------------- /test/IntegrationTests/Generator.Product.cs: -------------------------------------------------------------------------------- 1 | using Bogus; 2 | using SampleApp.Models; 3 | using System; 4 | 5 | namespace IntegrationTests 6 | { 7 | public static partial class Generator 8 | { 9 | public static Faker Product { get; } = 10 | new Faker("pt_BR") 11 | .StrictMode(true) 12 | .RuleFor(c => c.Id, f => 0) 13 | .RuleFor(c => c.Name, f => f.Commerce.Product()) 14 | .RuleFor(c => c.Price, f => Math.Round(f.Random.Decimal(3, 20), 2)); 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /test/IntegrationTests/IntegrationTests.csproj: -------------------------------------------------------------------------------- 1 |  2 | 3 | netcoreapp2.2 4 | false 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | -------------------------------------------------------------------------------- /test/IntegrationTests/ProductControllerTests.cs: -------------------------------------------------------------------------------- 1 | using FluentAssertions; 2 | using Microsoft.Extensions.DependencyInjection; 3 | using NUnit.Framework; 4 | using SampleApp.Models; 5 | using System.Linq; 6 | using System.Net; 7 | using System.Net.Http; 8 | using System.Threading.Tasks; 9 | 10 | namespace IntegrationTests 11 | { 12 | public class ProductControllerGetAllTests : BaseIntegrationTest 13 | { 14 | [Test] 15 | public async Task GetNotFound() 16 | { 17 | var repository = serviceProvider.GetService(); 18 | var allProducts = await repository.GetAllAsync(); 19 | foreach (var product in allProducts) 20 | await repository.DeleteAsync(product.Id); 21 | var response = await client.GetAsync("/api/products/3"); 22 | response.StatusCode.Should().BeEquivalentTo(HttpStatusCode.NotFound); 23 | } 24 | 25 | } 26 | 27 | public class ProductControllerGetOneTests : BaseIntegrationTest 28 | { 29 | private IProductsRepository repository; 30 | private HttpResponseMessage response; 31 | private Product product; 32 | 33 | [OneTimeSetUp] 34 | public async Task Setup() 35 | { 36 | repository = serviceProvider.GetService(); 37 | var allProducts = await repository.GetAllAsync(); 38 | foreach (var p in allProducts) 39 | await repository.DeleteAsync(p.Id); 40 | product = Generator.Product; 41 | await repository.CreateAsync(product); 42 | response = await client.GetAsync($"/api/products/{product.Id}"); 43 | } 44 | 45 | [Test] 46 | public void StatusCodeIsOk() => response.StatusCode.Should().BeEquivalentTo(HttpStatusCode.OK); 47 | 48 | [Test] 49 | public async Task ProductFound() 50 | { 51 | var productReturned = await response.Content.ReadAsAsync(); 52 | productReturned.Should().BeEquivalentTo(product); 53 | } 54 | } 55 | 56 | public class ProductControllerPostTests : BaseIntegrationTest 57 | { 58 | private IProductsRepository repository; 59 | private HttpResponseMessage response; 60 | private Product product; 61 | 62 | [OneTimeSetUp] 63 | public async Task Setup() 64 | { 65 | repository = serviceProvider.GetService(); 66 | var allProducts = await repository.GetAllAsync(); 67 | foreach (var p in allProducts) 68 | await repository.DeleteAsync(p.Id); 69 | product = Generator.Product; 70 | response = await client.PostAsJsonAsync($"/api/products/", product); 71 | } 72 | 73 | [Test] 74 | public async Task OnlyOneItemIsInDb() => (await repository.GetAllAsync()).Count().Should().Be(1); 75 | 76 | [Test] 77 | public void StatusCodeIsOk() => response.StatusCode.Should().BeEquivalentTo(HttpStatusCode.Created); 78 | 79 | [Test] 80 | public void LocationIsCorrect() => response.Headers.Location.ToString().Should().MatchRegex(@"http://localhost/api/Products/\d+"); 81 | 82 | [Test] 83 | public async Task ProductCreatedWasReturned() 84 | { 85 | var productReturned = await response.Content.ReadAsAsync(); 86 | productReturned.Name.Should().Be(product.Name); 87 | productReturned.Price.Should().Be(product.Price); 88 | } 89 | } 90 | } -------------------------------------------------------------------------------- /test/IntegrationTests/Setup.cs: -------------------------------------------------------------------------------- 1 | using Bogus; 2 | using Lambda3.AspNetCore.Mvc.Testing; 3 | using NUnit.Framework; 4 | using SampleApp; 5 | using System; 6 | using System.Threading.Tasks; 7 | 8 | namespace IntegrationTests 9 | { 10 | [SetUpFixture] 11 | public class Setup 12 | { 13 | private WebApplicationFactory webAppFactory; 14 | 15 | [OneTimeSetUp] 16 | public async Task OneTimeSetUp() 17 | { 18 | StartApiServer(); 19 | BaseIntegrationTest.WebAppFactory = webAppFactory; 20 | await webAppFactory.MigrateDbAndSeedAsync(); 21 | } 22 | 23 | private void StartApiServer() => webAppFactory = new WebApplicationFactory(inMemory: true).EnsureServerStarted(); 24 | 25 | [OneTimeTearDown] 26 | public void OneTimeTearDown() => webAppFactory?.Dispose(); 27 | } 28 | } 29 | 30 | -------------------------------------------------------------------------------- /test/IntegrationTests/WebApplicationFactoryExtensions.cs: -------------------------------------------------------------------------------- 1 | using Lambda3.AspNetCore.Mvc.Testing; 2 | using Microsoft.AspNetCore.TestHost; 3 | using System; 4 | using System.Collections.Generic; 5 | using System.Diagnostics; 6 | using System.Threading.Tasks; 7 | using Microsoft.Extensions.DependencyInjection; 8 | using static System.Console; 9 | using SampleApp.Models; 10 | using Microsoft.EntityFrameworkCore; 11 | using Microsoft.Extensions.Logging; 12 | using SampleApp; 13 | 14 | namespace IntegrationTests 15 | { 16 | public static class WebApplicationFactoryExtensions 17 | { 18 | public static async Task MigrateDbAndSeedAsync(this WebApplicationFactory webApplicationFactory) where TStartup : class 19 | { 20 | var services = webApplicationFactory.Host.Services; 21 | using (var scope = services.CreateScope()) 22 | { 23 | var scopedServices = scope.ServiceProvider; 24 | var db = scopedServices.GetRequiredService(); 25 | var logger = scopedServices.GetRequiredService>>(); 26 | await db.Database.EnsureCreatedAsync(); 27 | } 28 | } 29 | 30 | public static WebApplicationFactory EnsureServerStarted(this WebApplicationFactory webApplicationFactory) where TStartup : class 31 | { 32 | webApplicationFactory.CreateDefaultClient(); 33 | return webApplicationFactory; 34 | } 35 | 36 | } 37 | } 38 | -------------------------------------------------------------------------------- /test/UnitTests/Generator.Product.cs: -------------------------------------------------------------------------------- 1 | using Bogus; 2 | using SampleApp.Models; 3 | using System; 4 | 5 | namespace UnitTests 6 | { 7 | public static partial class Generator 8 | { 9 | public static Faker Product { get; } = 10 | new Faker("pt_BR") 11 | .StrictMode(true) 12 | .RuleFor(c => c.Id, f => 0) 13 | .RuleFor(c => c.Name, f => f.Commerce.Product()) 14 | .RuleFor(c => c.Price, f => Math.Round(f.Random.Decimal(3, 20), 2)); 15 | 16 | public static Faker ProductWithNegativePrice { get; } = 17 | new Faker("pt_BR") 18 | .StrictMode(true) 19 | .RuleFor(c => c.Id, f => 0) 20 | .RuleFor(c => c.Name, f => f.Commerce.Product()) 21 | .RuleFor(c => c.Price, f => Math.Round(f.Random.Decimal(-20, -3), 2)); 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /test/UnitTests/ProductControllerTests.cs: -------------------------------------------------------------------------------- 1 | using FluentAssertions; 2 | using Microsoft.AspNetCore.Mvc; 3 | using Moq; 4 | using NUnit.Framework; 5 | using SampleApp.Controllers; 6 | using SampleApp.Models; 7 | using System.Collections.Generic; 8 | using System.Net; 9 | using System.Threading.Tasks; 10 | 11 | namespace UnitTests 12 | { 13 | public class ProductControllerTests 14 | { 15 | [Test] 16 | public async Task GetAllSucceeds() 17 | { 18 | // arrange 19 | var productsRepositoryMock = new Mock(); 20 | var expectedProducts = new List(); 21 | productsRepositoryMock.Setup(pr => pr.GetAllAsync()).ReturnsAsync(expectedProducts); 22 | var productsController = new ProductsController(productsRepositoryMock.Object); 23 | // act 24 | var productsRetrieved = await productsController.GetProduct(); 25 | // assert 26 | ((OkObjectResult)productsRetrieved.Result).Value.Should().BeSameAs(expectedProducts); 27 | } 28 | 29 | [Test] 30 | public async Task GetOneSucceeds() 31 | { 32 | // arrange 33 | Product product = Generator.Product; 34 | var productsController = new ProductsController(Mock.Of(pr => pr.GetAsync(1) == Task.FromResult(product))); 35 | // act 36 | var productRetrieved = await productsController.GetProduct(1); 37 | // assert 38 | productRetrieved.Value.Should().Be(product); 39 | } 40 | 41 | [Test] 42 | public async Task PostSucceedsReturnsCorrectStatusCode() 43 | { 44 | // arrange 45 | var productsRepositoryMock = new Mock(); 46 | Product product = Generator.Product; 47 | productsRepositoryMock.Setup(pr => pr.CreateAsync(product)).ReturnsAsync(true); 48 | var productsController = new ProductsController(productsRepositoryMock.Object); 49 | // act 50 | var result = await productsController.PostProduct(product); 51 | // assert 52 | ((CreatedAtActionResult)result.Result).StatusCode.Should().Be((int)HttpStatusCode.Created); 53 | } 54 | 55 | [Test] 56 | public async Task PostSucceedsReturnsProduct() 57 | { 58 | // arrange 59 | var productsRepositoryMock = new Mock(); 60 | Product product = Generator.Product; 61 | productsRepositoryMock.Setup(pr => pr.CreateAsync(product)).ReturnsAsync(true); 62 | var productsController = new ProductsController(productsRepositoryMock.Object); 63 | // act 64 | var result = await productsController.PostProduct(product); 65 | // assert 66 | ((CreatedAtActionResult)result.Result).Value.Should().Be(product); 67 | } 68 | 69 | [Test] 70 | public async Task PostSucceedsReturnsCorrectRoute() 71 | { 72 | // arrange 73 | var productsRepositoryMock = new Mock(); 74 | Product product = Generator.Product; 75 | product.Id = 3; 76 | productsRepositoryMock.Setup(pr => pr.CreateAsync(product)).ReturnsAsync(true); 77 | var productsController = new ProductsController(productsRepositoryMock.Object); 78 | // act 79 | var result = await productsController.PostProduct(product); 80 | // assert 81 | ((CreatedAtActionResult)result.Result).RouteValues.Should().Contain("id", 3); 82 | } 83 | 84 | [Test] 85 | public async Task PostSucceedsSavesToRepository() 86 | { 87 | // arrange 88 | var productsRepositoryMock = new Mock(); 89 | Product product = Generator.Product; 90 | var productsController = new ProductsController(productsRepositoryMock.Object); 91 | // act 92 | var result = await productsController.PostProduct(product); 93 | // assert 94 | productsRepositoryMock.Verify(pr => pr.CreateAsync(product)); 95 | } 96 | 97 | [Test] 98 | public async Task PostWithProductWithNegativePriceReturnsBadResult() 99 | { 100 | // arrange 101 | var productsRepositoryMock = new Mock(MockBehavior.Strict); 102 | Product product = Generator.ProductWithNegativePrice; 103 | productsRepositoryMock.Setup(pr => pr.GetAsync(1)).ReturnsAsync(product); 104 | var productsController = new ProductsController(productsRepositoryMock.Object); 105 | // act 106 | var result = await productsController.PostProduct(product); 107 | // assert 108 | ((StatusCodeResult)result.Result).StatusCode.Should().Be((int)HttpStatusCode.BadRequest); 109 | } 110 | } 111 | } -------------------------------------------------------------------------------- /test/UnitTests/ProductTests.cs: -------------------------------------------------------------------------------- 1 | using FluentAssertions; 2 | using NUnit.Framework; 3 | using SampleApp.Models; 4 | 5 | namespace UnitTests 6 | { 7 | public class ProductTests 8 | { 9 | // |---------arrange----------|-----act----|-----assert-----| 10 | [Test] public void IsExpensive() => new Product { Price = 1004 }.IsExpensive.Should().BeTrue(); 11 | 12 | [Test] public void IsExactlyExpensive() => new Product { Price = 1000 }.IsExpensive.Should().BeTrue(); 13 | 14 | [Test] public void IsNotExpensive() => new Product { Price = 4 }.IsExpensive.Should().BeFalse(); 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /test/UnitTests/UnitTests.csproj: -------------------------------------------------------------------------------- 1 |  2 | 3 | netcoreapp2.2 4 | false 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | --------------------------------------------------------------------------------