How to complete an existing phpunit test with a generator

621 views Asked by At

PhpUnit has a generator of skel based on an existing class.

But it's works once.

If later some new method are added (because a dev doesnt work with tdd ), the test file is incomplete.

Is there a tool to generate a skel for uncovered method ?

2

There are 2 answers

2
Darren Cook On

AFAIK there is no built-in phpunit functionality to updated the auto-generated test code; that is typical of most code generators.

The good news is that each of the functions is added quite cleanly and independently. So what I would do is rename your existing unit test file to *.old, regenerate a fresh test file, then use meld (or the visual diff tool of your choice) to merge in the new functions.

Aside: automatic test generation is really only needed at the start of a new class anyway; the idea of exactly one unit test per function is more about generating nice coverage stats to please your boss; from the point of view of building good software, some functions will need multiple tests, and some functions (getters and setters come to mind) do not really need any, and sometimes multiple functions are best covered by a single unit test (getters and setters again come to mind).

2
Sven On

I don't know any, and I also don't see the need. That skeleton generator generates one test method per function it finds, but you cannot test all use cases of a slightly advanced function within only one test function.

Also, the name of the test function is generated - but better names can and should be created to describe the intended test case or behavior of the tested function. Like "testGetQuoteFromStockMarket" vs. "testGettingMicrosoftQuoteFromStockMarketShouldReturnQuoteObject" and "testGettingUmbrellaCorporationFromStockMarketShouldFailWithException".

Note that you cannot test the throwing of exceptions in combination with cases that do not throw exceptions.

So all in all there simply is no use case to create "one test method per method" at all, and if you add new methods, it is your task to manually add the appropriate number of new tests for that - the generated code coverage statistics will tell you how well you did, or which functions are untested.