如何为新的 MVC 框架创建单元测试
我最近一直在学习 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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
只需编写测试类,最好反映您的框架结构(例如
ControllerTest
、ModelTest
等),使类通过其步伐,这意味着输入一些数据并检查输出。如果您的代码结构良好,应该很容易实现。编辑
基本上,您在单元测试中测试的内容是
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 usingob_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.