测试Catalyst REST API的最简单方法是什么?

时间:2011-11-29 03:16:48

标签: json perl http testing catalyst

我正在使用Catalyst::Controller::REST构建RESTful Web服务。通常对于Web测试我使用Test::WWW::Mechanize,但这似乎更适合“GET / POST HTML RPC”测试。是否有任何测试模块可以使用基本身份验证来测试HTTP,使用GET / POST / PUT / DELETE等和JSON轻松?也许是与Catalyst / PSGI很好地集成的东西,所以我不必启动网络服务器?

2 个答案:

答案 0 :(得分:7)

Catalyst :: Test是LWP :: UserAgent的子类。以下内容应该给你正确的想法:

#!/usr/bin/env perl
use warnings;
use strict;

use Test::More;
use Catalyst::Test 'MyApp';
use HTTP::Request::Common;
use JSON::Any; # or whatever json module you usually use
my $data = 'some_json_data_here';
my $res = request(
    POST '/some_path',
    Content_Type => 'text/xml',
    Content => $data,
);

my $content = json_decode($res->content); # or whatever, can't remember the interface.
my $expected = "some_data";
is_deeply ( $content, $expected); 

答案 1 :(得分:1)

或者用更现代的说法:

  my $data = '{"username":"xyz","password":"xyz"}';
  my $res = request
    (
     POST '/bar/thing',
     Content_Type => 'application/json',
     Content => $data,
    );