如何为新的 MVC 框架创建单元测试

发布于 2024-12-03 07:55:19 字数 296 浏览 0 评论 0原文

我最近一直在学习 MVC,并开始从 http://anantgarg.com/2009/03/13/write-your-own-php-mvc-framework-part-1/

我希望能够扩展这些基类,但首先我希望能够对它们进行单元测试。有谁知道我将如何测试基本控制器、模型和模板类?

提前致谢!

I have been learning MVC recently and have started creating my own framework (for learning purposes only, of course) from http://anantgarg.com/2009/03/13/write-your-own-php-mvc-framework-part-1/

I want to be able to extend these base classes but first I would like to be able to unit test them. Does anyone have an idea how I would go about testing the base Controller, Model and Template classes?

Thanks in advance!

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

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

发布评论

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

评论(1

恍梦境° 2024-12-10 07:55:19

只需编写测试类,最好反映您的框架结构(例如 ControllerTestModelTest 等),使类通过其步伐,这意味着输入一些数据并检查输出。如果您的代码结构良好,应该很容易实现。

编辑

基本上,您在单元测试中测试的内容是 if ( Class::methodToTest( $input ) === $expected_output )。对于相同的$input,输出必须始终相同。如果情况并非如此,或者您无法测试编写这样的测试用例,则通常表明您的代码结构不佳(面向对象且松散耦合)。

例如,您的 Template::render() 方法是不可测试的,因为它打印数据而不是返回数据。现在,您可以使用 ob_start() 来解决这个问题,但更好的方法是将函数分成更小的部分,返回值而不是直接打印它们。

虽然有点抽象,但希望你能明白其中的意思。

Just write test classes, preferably mirroring your framework structure (eg ControllerTest, ModelTest, etc), that put the classes through their paces, meaning putting in some data and checking the output. If your code is well-structured, should be quite easy to implement.

Edit

Basically, what you test in a unit test is if ( Class::methodToTest( $input ) === $expected_output ). The output must always be identical for the same $input. If this is not the case, or you can't test write a test case like this, it's often an indicator that your code is not well structured (object oriented and loosely coupled).

Your Template::render() method for example, is not testable because it prints the data instead of returning it. Now, you could work around this by using ob_start(), but better anyway would be to chop the function into smaller parts, that return values instead of directly printing them.

It's a bit abstract, but I hope you get the point.

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