Mock request object in test case

21 views
Skip to first unread message

iktiar rahman

unread,
May 10, 2018, 5:11:05 AM5/10/18
to Mojolicious
I have a  Mojolicious app.

with a controller that calls new(), init() method of path.pm
In path.pm i can use '$self->req->headers->user_agent' and other functions to initialize.

1. basecontroller.pm  [controller]
2. path.pm module 

Path.pm module, that module has one init method
 
Enter code here...
#basecontroller.pm

//calls path.pm . new()
//calls path.pm  init()

#path.pm

sub new () {
 
..
  $self
->init();
}

sub init {
     
my $x_forwarded_host = 'x-forwarded-host';
   
    $self->{data} = {
        user_agent  => $self->req->headers->user_agent,
        cookie      => $self->req->headers->cookie || '',
        path_info   => $self->req->{url}->{path}->{path} || '',
        referer     => $self->req->{content}->{headers}->{headers}->{$x_forwarded_host} || '', 
        query_str   => $self->req->{url}->{query}->{string} || '',
    };

}

Problem is when unit testing the path.pm

It cannot finds the '$self->req' object method, which is right.
Can't locate object method "req" via package



How can i mock
$self->req->headers
$self->req->headers->cookie
$self->req->{url}->{path}->{path}
$self->req->{url}->{query}->{string}

My test code: 

Enter code here...#mock Mojolicious app
    my $mock = Mojolicious->new;
   
    subtest "init, Test" => sub {
        # test for initialization
        my $path = Path->new($mock);

        $ENV{'SERVER_ID'} = '1';
        $path->init();
        isa_ok $path->{data}, 'HASH', 'data type, ok';
        is $path->{data}->{server_id}, $ENV{'SERVER_ID'}, 'SERVER_ID, ok';
        is $path->{data}->{path_info}, '', 'PATH_INFO, ok';
        
    };





Reply all
Reply to author
Forward
0 new messages