在 Dancer2 应用程序中存根/模拟服务

发布于 2025-01-09 13:43:37 字数 1311 浏览 0 评论 0原文

通常,我有一个与此类似的设置:

#!/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 技术交流群。

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

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文