使用 Test::More 测试 autoload 提供的方法
我有一个工厂类,它通过使用自动加载提供了一堆类似的方法。对于不同对象类型的较长列表,它可以执行类似“
Factory->objects();
Factory->object(23);
Factory->object(name => "foo");
现在我想为此类编写测试”之类的操作。我从这样开始:
use Test::More;
BEGIN { use_ok 'Factory' }
my $objects = Factory->objects;
# more tests following ...
测试在 Factory->objects
行中失败,因为它隐式检查 Factory
是否可以执行 objects()
>。我找不到这方面的一些文档。但如果我在非测试脚本中运行相同的调用,它就可以完美工作。
如何测试这个?
更新: ARGH,我刚刚意识到我将所有这些都放入了 Catalyst 应用程序中 Factory
模型类的测试中。好吧,这个模型类是我的外部模型(我实际上打算测试)中的 Factory
类的适配器。该作品非常适合模型本身。仍然很高兴知道如何测试改编类中的方法。适配器类如下所示:
package MyCatalystApp::Model::Factory;
use Moose;
extends 'Catalyst::Model';
extends 'Catalyst::Model::Adaptor';
__PACKAGE__->config(class => 'MyModel::Factory');
MyModel::Factory
与原始问题中的 Factory
是同一类。为了简化起见,我跳过了原始问题中 Catalyst 和模型之间的差异。
I have a factory class which provides a bunch of similar methods by using autoload. For a longer list of different object types it can do things like
Factory->objects();
Factory->object(23);
Factory->object(name => "foo");
Now I want to write a test for this class. I started with something like this:
use Test::More;
BEGIN { use_ok 'Factory' }
my $objects = Factory->objects;
# more tests following ...
The test fails in the line with Factory->objects
because it implicitly checks if Factory
can do objects()
. I could not find some documentation for this. But if I run the same call in a non-testing script it works perfectly.
How to test this?
Update: ARGH, I've just recognized I put all of this in the test for the Factory
model class in my Catalyst app. Well, this model class is an Adapter for the Factory
class in my external model (which I actually intended to test). The work perfectly for the model itself. Still would appreciate to know how to test method from an adapted class. This is how the adapter class looks like:
package MyCatalystApp::Model::Factory;
use Moose;
extends 'Catalyst::Model';
extends 'Catalyst::Model::Adaptor';
__PACKAGE__->config(class => 'MyModel::Factory');
MyModel::Factory
is the same class as Factory
in the original question. I skipped the difference between Catalyst and the model in the original question for simplification.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您只需在调用测试之前(在
use_ok
之后)添加“use Factory;
”即可。You should simply add "
use Factory;
" before calling the tests (afteruse_ok
).Catalyst 在 setup_components 期间通过调用 COMPONENT 方法。我猜 Catalyst::Model::Adapter 依赖于这种情况的发生。
当您
使用 MyCatalystApp::Model::Factory
时,您可以在测试中调用my $factory = MyCatalystApp::Model::Factory->COMPONENT()
而不是new()
来使它们工作。Catalyst instantiates models (components) during setup_components by calling the COMPONENT method. I guess Catalyst::Model::Adaptor relies on this happening.
When you
use MyCatalystApp::Model::Factory
you can get away with callingmy $factory = MyCatalystApp::Model::Factory->COMPONENT()
from within tests instead ofnew()
to make them work.