SLIDE 1 @stevejgordon www.stevejgordon.co.uk
MICROSOFT DEVELOPER TECHNOLOGIES MVP
Steve Gordon
Applying T est Driven Development (TDD) with Integration T ests
SLIDE 2 t h s
Test Driven Development (TDD) Applying TDD with integration tests Defining external boundaries Creating fakes of external services Replacing services with fakes by customizing the test client
Overview
SLIDE 3
Test Driven Development
SLIDE 4
Retrospective Tests
Tests written after implementation code Possible to miss test cases Possible to assert on incorrect output
SLIDE 5
Test Driven Development
Tests come before implementation code Test coverage aligned to requirements Simplified implementation code Promotes refactoring to clean code
SLIDE 6
Red Green Refactor
Test Driven Development Cycle
SLIDE 7 Mental shift from retrospective testing Requires perseverance to become productive
TDD Paradigm
SLIDE 8
SLIDE 9 Demo
t h s
Apply test driven development
- Write a failing test (red)
- Make the test pass (green)
- Refactor the code
SLIDE 10
Add GET endpoint /api/stock/total Return JSON (application/json) response Total is count of all stock of all products
{ "stockItemTotal": 100 }
SLIDE 11 Demo
t h s
Continue development with TDD
- Test and implement a final requirement
Define a boundary for integration tests Create a fake of a dependency
SLIDE 12 High-level Architecture
SDK
SLIDE 13 Code Dependency Chain
IDatabaseClient<T> ICloudDatabase IProductDataRepository StockController
SLIDE 14 Code Dependency Chain
IDatabaseClient<T> ICloudDatabase IProductDataRepository StockController
SLIDE 15 Code Dependency Chain
IDatabaseClient<T> ICloudDatabase IProductDataRepository StockController
SLIDE 16
Advantages
Integration tests run fully in memory Can be run often during development Easy to run during continuous integration
SLIDE 17 Demo
t h s
Customize the test client using WithWebHostBuilder
SLIDE 18 ISe IServic iceColle llectio ion ISe IServic iceColle llectio ion ICloudDatabase -> CloudDatabase
Service Registration Order
ISe IServic iceColle llectio ion ICloudDatabase -> CloudDatabase ISomeOtherService -> SomeOtherService ISe IServic iceColle llectio ion ICloudDatabase -> CloudDatabase ISomeOtherService -> SomeOtherService ICloudDatabase -> FakeCloudDatabase Startup.cs
ConfigureServices
StockControllerTests.cs
ConfigureTestServices
SLIDE 19 var client = _factory.WithWebHostBuilder(builder => { builder.ConfigureTestServices(services => { services.RemoveAll<IFoo>(); services.AddSingleton<IFoo,FakeFoo>(); }); }).CreateClient();
Managing Registered Services
SLIDE 20
SLIDE 21 t h s
Learned about Test Driven Development Applied the TDD cycle
- Wrote a failing test
- Implemented with minimal code
- Confirmed the test passed
- Refactored where necessary
Defined external boundary for testing Created a fake for a service Customized the test client to use the fake
Summary
SLIDE 22
Up Next: Writing Integration Tests for ASP.NET Core Web APIs: Part 2