PerlDancer / PerlDancer/Dancer2

How to stub a service in Dancer?

Open
#1,640 0 comments 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

Question
Dominant language
Perl
Stars
604
Forks
288
Avg merge
1d 5h
Merged PRs (30d)
5

Description

I would want to stub services my actions use. I asked at stackoverfow, so I hope you don't mind me posting this here, too:

https://stackoverflow.com/questions/71225977/stubbing-mocking-a-service-in-a-dancer2-application

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?

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

The issue names no Dancer2 source file, test, or entry point; start with the linked Stack Overflow question and the shown Demo, Stub, and Plack::Test example. Done would require documenting a project-supported way to replace the service during a Plack::Test request, but no file or acceptance test is specified.

Written by the indexing model from the issue text.

Assessment

Tech stack
perl
Domain
backend, testing
Issue type
Documentation
Difficulty
4/5
Estimated time
3-5 days
Activity status
Stale
Clarity
Needs clarification
Newbie friendliness
25/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.