对返回 SQL 的类进行单元测试

发布于 2024-09-15 03:12:02 字数 799 浏览 5 评论 0原文

我正在尝试使用 PHPUnit 对一些返回 SQL 的类方法进行单元测试。这些类应该与任何 Zend_Db 适配器一起使用,所以我希望测试也能这样做。我的测试看起来有点像这样:

public function testEtcGeneratesCorrectSQL()
{
    $model = new ClassBeingTested();

    // do some stuff

    $sql = $model->__toString();

    $this->assertEquals('SELECT foo.* FROM foo WHERE bar = 1', $sql);
}

问题是适配器之间转义的差异。如果我使用 Pdo_Mysql 运行此测试,我会收到如下错误:

--- Expected
+++ Actual
@@ @@
-SELECT foo.* FROM foo WHERE bar = 1
+SELECT `foo`.* FROM `foo` WHERE `bar` = 1

如果我使用 Sqlite 适配器:

--- Expected
+++ Actual
@@ @@
-SELECT foo.* FROM foo WHERE bar = 1
+SELECT "foo".* FROM "foo" WHERE "bar" = 1

那么这里应该做什么?有没有办法禁用 Zend_Db 中的转义,我可以仅为这些测试的目的而打开它?我是否需要对适配器类型进行硬编码,然后调整我的预期输出以匹配?或者在进行断言之前删除不同的引号字符?

I'm trying to use PHPUnit to unit test some class methods that return SQL. These classes should work with any Zend_Db adapter, so I would like the tests to do the same. My tests look a little like this:

public function testEtcGeneratesCorrectSQL()
{
    $model = new ClassBeingTested();

    // do some stuff

    $sql = $model->__toString();

    $this->assertEquals('SELECT foo.* FROM foo WHERE bar = 1', $sql);
}

the problem is differences in escaping between adapters. If I run this test using Pdo_Mysql, I'll get an error like this:

--- Expected
+++ Actual
@@ @@
-SELECT foo.* FROM foo WHERE bar = 1
+SELECT `foo`.* FROM `foo` WHERE `bar` = 1

if I use the Sqlite adapter:

--- Expected
+++ Actual
@@ @@
-SELECT foo.* FROM foo WHERE bar = 1
+SELECT "foo".* FROM "foo" WHERE "bar" = 1

so what's the right thing to do here? Is there a way to disable the escaping in Zend_Db I can turn on just for the purpose of these tests? Do I hardcode in the adapter type and then adjust my expected output to match? Or strip out the different quote characters before doing the assertion?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

横笛休吹塞上声 2024-09-22 03:12:02

使用常量而不是硬编码任一组引号,因此对于 MySQL:

$this->assertEquals('SELECT ' . DB_QUOTE . 'foo' . DB_QUOTE . '.* FROM '
                    . DB_QUOTE . 'foo' . DB_QUOTE . ' WHERE '
                    . DB_QUOTE . 'bar' . DB_QUOTE . ' = 1');

这看起来绝对可怕,但如果您根据所使用的驱动程序设置 DB_QUOTE ,它将起作用。

Use a constant rather than hardcoding either set of quotes, so for MySQL:

$this->assertEquals('SELECT ' . DB_QUOTE . 'foo' . DB_QUOTE . '.* FROM '
                    . DB_QUOTE . 'foo' . DB_QUOTE . ' WHERE '
                    . DB_QUOTE . 'bar' . DB_QUOTE . ' = 1');

Which looks absolutely horrid, but it will work if you set DB_QUOTE depending on the driver you're using.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文