在 Dancer2 应用程序中存根/模拟服务
通常,我有一个与此类似的设置:
#!/usr/bin/env perl
package Demo;
use Dancer2;
use Moose;
sub get($self, $params) {
my $whatever = ...; # connect with db and do stuff
return $whatever;
}
my $service = Demo->new();
sub make_web_friendly($param) { # no $self, here!
return "Hello $param!";
}
get '/' => sub {
my $response = $service->get(query_parameters);
return make_web_friendly($response);
};
start;
这样,我可以很好地分离关注点,并且我的服务可以测试,而无需通过 Plack::Test 处理虚假的 Web 请求;
然而,每当我测试请求时,我总是也会测试服务,这违背了这种分离。
我想为 Plack 测试提供一个模拟服务答案的存根服务。因此(我假设)我要么可以以某种方式使 get 操作 $self
感知,要么必须将模拟的服务传递给 Plack。
# this is put together to showcase the principle, it does not work
package Stub {
use Moose;
use Test::More;
use Data::Dumper;
sub get($self, $params) {
diag "I received:" . Dumper($params);
return "Bianca!";
}
}
my $app = Demo->to_app;
my $test = Plack::Test->create($app);
my $stub = Stub->new();
$test->service($stub);
my $request = HTTP::Request->new( GET => '/' );
my $response = $test->request($request);
is $response, 'Hello, Bianca', 'Bianca was here';
我怎样才能实现(类似的)这个目标?
Usually, I have a setup similar to this:
#!/usr/bin/env perl
package Demo;
use Dancer2;
use Moose;
sub get($self, $params) {
my $whatever = ...; # connect with db and do stuff
return $whatever;
}
my $service = Demo->new();
sub make_web_friendly($param) { # no $self, here!
return "Hello $param!";
}
get '/' => sub {
my $response = $service->get(query_parameters);
return make_web_friendly($response);
};
start;
This way, I can separate concerns pretty well and my services are testable without going over a bogus web request via Plack::Test;
However, whenever I test the request, I always also test the service, with goes against this separation.
I would want to provide the Plack Test with a stubbed service that would mock a service answer. So (I assume) either I can make the get action somehow $self
-aware, or would have to pass the mocked service to Plack.
# this is put together to showcase the principle, it does not work
package Stub {
use Moose;
use Test::More;
use Data::Dumper;
sub get($self, $params) {
diag "I received:" . Dumper($params);
return "Bianca!";
}
}
my $app = Demo->to_app;
my $test = Plack::Test->create($app);
my $stub = Stub->new();
$test->service($stub);
my $request = HTTP::Request->new( GET => '/' );
my $response = $test->request($request);
is $response, 'Hello, Bianca', 'Bianca was here';
How can I achieve (something like) this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论