Red, Green, Refactor!
Test->Code -> Refactor
Need to change your mindset
Because the tests have to be written we need to stop and think about what we have to implement. This encourages better design.
Code is a bit less of a black box
Test code 101
public class ObjectUnderTestTests
public void MethodUnderTest_State_ExpectedBehaviour()
The TDD Mindset
Huge shift in development approach
- ALWAYS write a test before writing code
- always run your test
- Fix failing tests as soon as possible
What do we test?
- Everything! In isolation
- Express how we want to interact with the code
- small, isolated section of functionality
- Single test should not be testing too much
What not to do!
Showed a demo from Scott Gutheries blog showing a page load doing everything. Not possible to test.
Showed how cruise control can be used to automatically run all tests
You need to have a controller set on top of the repository.
Testing in Isolation: Test Doubles
More flexibility for testing the application.
Dummy Objects, Stubs, Mocks, Fakes.
A Stub acts as a stand in
Mocks are powerful normally development using a framework.
Normal: Business Logic --> Data Layer
Test Dobule: Business Logic -> IData
IData -> DataLayer
IData -> Double (Pretends to be the data layer)
We now want to send an email after successfully insertion.
We have an interface which implements SendInsertNotification
The controller then takes a interface in the constructor - the test service then is used.
You can get a hold of a realistic stub email service which will open port 25 etc.
Would we be creating a stub for the database? Recommended not to. But we do still want to be testing in isolation. So in the Business Layer we use the mocked data layer, and in the data layer we use the real implementation.
These could fail for other reasons, like network going down etc.
When testing the database you can use a tear down method which can clean the database and reseed all ids.
You can also create [Setup] code which will initiate everything
NCover will use the profiler API to monitor what lines of code are being called an those which aren't.