How to "connect" embedded user agent to application being tested?

15 views
Skip to first unread message

Edward Baudrez

unread,
Oct 22, 2020, 4:40:10 AM10/22/20
to Mojolicious
Hello, I have a controller that uses the '->ua' helper to fetch data on demand. During testing, I provide a mock service to avoid fetching the data from a real service on the internet. The mock service is mounted under the application to be tested using the 'Mount' plugin.

However, the 'embedded' user agent ('->ua') doesn't seem to 'see' the mocked service. I have tried and stripped down my problem to the following:

----------------------------------------
use Mojo::Base -strict;
use Test::Mojo;                                                                                                 
use Test::More;
{
    package MyApp;
    use Mojo::Base 'Mojolicious';
    sub startup {
        my $self = shift;
        $self->routes->get('/welcome' => sub { shift->render(text => 'welcome!') });            
        $self->routes->get('/indirect' => sub {                                               
                my $self = shift;
                my $got = $self->ua->get('/welcome')->result->text;
                $self->render(text => $got);
        });
    }
}
my $t = Test::Mojo->new('MyApp');
$t->get_ok('/welcome')->status_is(200)->content_is('welcome!'); # this test passes
$t->get_ok('/indirect')->status_is(200)->content_is('welcome!'); # **THIS TEST FAILS**
done_testing;
----------------------------------------

The second test fails. The embedded user agent ('->ua') doesn't seem to be connected to the application object inside the Test::Mojo object ('$t->app') at all. (If I try printing available routes from within the controller with '$self->ua->server->app->routes', there seem to be none.) I tried various combinations of setting '$t->app', '$t->ua', '$t->ua->server->app', but couldn't find anything that worked.

What do I need to do to get this working?


Kind regards
Edward

Sebastian Riedel

unread,
Oct 22, 2020, 5:07:28 AM10/22/20
to Mojolicious
                my $got = $self->ua->get('/welcome')->result->text;

Relative URLs are resolved by the user agent to $self->ua->server->app, which in this case is probably a Mojo::HelloWorld instance. I strongly suggest you use a custom service class with its own Mojo::UserAgent instance as an attribute. Then make the full service base URL configurable and just set it to $app->foo_service->ua->server->url. Or similar... you get the idea.

--
sebastian
Reply all
Reply to author
Forward
0 new messages