Testing a query builder
I am building a query builder that I want to unit test.
I don't know how 开发者_运维技巧to go about it though.It (currently) consists of two parts: the QueryBuilder
itself which provides a fluent interface for constructing queries. And a SqlConstructor
that takes care of constructing the actual SQL.
So basically, how do I test 'correctness'? Should I just test for the existence of keywords? (Like, select
being the first keyword in a select-type query?) I think to test correctly, there are a whole lot of things that are important, like the order in which keywords appear etc. etc.
You test that for a given input, there is an expected output.
If I understand correctly, your QueryBuilder is collecting query parts, so make sure the datastructure holding these parts actually contains them when you add them through the QueryBuilder's method. If it has a addWhereClause
method or something like that, check that the method actually does, what you wrote into the method body, e.g. write a test like
public function testWhereMethodAddsExpressionToPartsArray()
{
$expression = 'foo = "bar"';
$this->sut->where($expression);
$parts = $this->sut->getParts('where');
$this->assertContains($expression, $parts);
}
For the SqlConstructor do the same, test that the input it gets from the datastructure you filled with the QueryBuilder (you might wanna mock it for that) produces the expected output.
If you want to test for actual validity of the SQL, write a separate testcase for that. Keep in mind that it's not the purpose of a UnitTest to ensure the SQL is correct, but that your SQLGenerator generates the SQL in the way you told it to generate it.
The problem when validating the SQL is, SQL is complex. It has a formal grammar. How much of that grammar would your test cases cover? Writing a parser for SQL doesn't sound too feasible to me, let alone one that is complete.
Related:
- Test Cases for
Zend_Db_Select
精彩评论