测试不存在的代码[关闭]

TDD claims that I should write tests first. Say I want to write a service, how do I start writing tests for the service if I don't have anything yet at all? What would be the first test? An attempt to instantiate the service and get an exception?

PHP Laravel-based example:

class ServiceTest extends TestCase
{
    public function testServiceExists()
    {
        $service = App::make('grid');
    }
}

Result:

PHPUnit 5.5.4 by Sebastian Bergmann and contributors.

E 1 / 1 (100%)

Time: 123 ms, Memory: 14.00MB

There was 1 error:

1) ServiceTest::testServiceExists ReflectionException: Class grid does not exist

/home/supertrall/domains/md.local/laravel/vendor/laravel/framework/src/Illuminate/Container/Container.php:749 /home/supertrall/domains/md.local/laravel/vendor/laravel/framework/src/Illuminate/Container/Container.php:644 /home/supertrall/domains/md.local/laravel/vendor/laravel/framework/src/Illuminate/Foundation/Application.php:709 /home/supertrall/domains/md.local/laravel/vendor/laravel/framework/src/Illuminate/Support/Facades/Facade.php:237 /home/supertrall/domains/md.local/laravel/tests/Grid/ServiceTest.php:20

ERRORS! Tests: 1, Assertions: 0, Errors: 1.

Encountering such errors is a good thing in TDD. It's implying that you need to resolve the error just in order to encounter another one.

When coding in TDD, you program by wishful thinking. In other words, you write some code that uses a component, before you implement the component itself. This helps to discover what functions and data you need, and following this discovery will lead you to more simple and useful APIs.

Even though the TDD concepts are not very hard to learn, getting used to TDD's test-first development approach is hard and time-consuming. You're on the right track, just read more and test more to become comfortable with the methodology.

You are on the right way!

TDD is a methodology. It requires a set of disciplines, and one of them is red, green, refactor. It is about writing test first, make it pass and then refactor the code.

  • ‘Red’ – write failing test
  • ‘Green’ – make the test pass
  • ‘Refactor’ – clean up your code

Yes, that a class should exists could be a test also!

Some info about at: