*Updated* 2 Mai 2011: The "dynamic" keyword in C#4 was not meant to be used in the below scenario. Use VS2010 code completion instead.
We know that if you are using TDD, then you should write your test before you are implementing anything else, don’t we :-)
Figure: 1. Write a failing test (red), 2. Make the test pass (green), 3. Refactor your code
But if you are thinking about new methods, you can’t really run the tests because your unit test wont compile, see the following example.
[TestMethod()]
public void CalculatorThingAdd_2PositiveNumbers_ResultAdded()
{
// Arrange
CalculatorThing myCalculator = new CalculatorThing();
int result = 0;
int expcected = 3;
// Act
result = myCalculator.Addition(1, 2);
// Assert
Assert.AreEqual(result, expcected);
}
BAD code example: In TDD I would like to run this test, before I implement the method “Addition”
On compiling this test, you get the following error message
Error 1 'ConsoleApplication.CalculatorThing' does not contain a definition for 'Addition' and no extension method 'Addition' accepting a first argument of type 'ConsoleApplication.CalculatorThing' could be found (are you missing a using directive or an assembly reference?)
Figure: Code want compile, because “Addition” is not implemented, and C# is static type safe on compile time
But you can avoid this by using the dynamic keyword, see below
[TestMethod()]
public void CalculatorThingAdd_2PositiveNumbers_ResultAdded()
{
// Arrange
dynamic myCalculator = new CalculatorThing();
int result = 0;
int expcected = 3;
// Act
result = myCalculator.Addition(1, 2);
// Assert
Assert.AreEqual(result, expcected);
}
GOOD code example: This code compiles nicely
Figure: Code compiles, because myCalculator is a dynamic object and evaluated on runtime not on compile time
But if you run this test you get:
Figure: Test failed because method not implement
Test method CalculatorConsole.Tests.CalculatorTest.CalculatorThingAdd_2PositiveNumbers_ResultAdded threw exception:
Microsoft.CSharp.RuntimeBinder.RuntimeBinderException: 'ConsoleApplication.CalculatorThing' does not contain a definition for 'Addition'
NICE!!!!
We have a failing test!
Now go and implement the method and make the test pass!