You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Plack::Test中设置序列化格式的POST请求内容?Dancer2 REST应用测试数据为空导致数据库约束错误

如何在Plack::Test中设置序列化格式的POST请求内容?Dancer2 REST应用测试数据为空导致数据库约束错误

看起来你遇到的问题核心是测试代码里的POST请求没有正确按照JSON格式传递数据,导致Dancer2没法正确解析请求体,最终后端拿到的email字段为null,触发了PostgreSQL的非空约束错误。我来帮你一步步解决这个问题:

问题根源分析

你当前的测试代码有两个关键错误:

  • 误用了Storable::freeze序列化数据:这是Storable的二进制序列化格式,完全不符合Dancer2配置的JSON serializer预期的格式,后端自然没法解析出正确的字段值
  • 请求的Content-Type不正确:你的请求默认使用了application/x-www-form-urlencoded,而Dancer2只有在看到application/json的Content-Type时,才会用JSON解析器去处理请求体

修正后的测试代码

你需要调整请求构造的方式,改用JSON序列化数据,并设置正确的请求头:

use strict;
use warnings;
use Test::More;
use Test::Deep;
use Plack::Test;
use Plack::Util;
use HTTP::Request::Common;
use JSON::MaybeXS qw(decode_json encode_json);
use Data::Dumper qw(Dumper);
use utf8;
use MyApp;

my %data = (
    password => 'A12345678',
    email    => 'test@test.com'
);

# APP Start
my $app  = MyApp->to_app;
my $test = Plack::Test->create($app);

subtest register => sub {
    print ">>> Test <<<\n";

    my $datas = {
        password => $data{password},
        email    => $data{email},
    };

    # 改用JSON序列化数据,替代Storable::freeze
    my $serialized_data = encode_json($datas);
    
    # 构造POST请求时,指定Content-Type并传递JSON请求体
    my $res = $test->request(
        POST '/api/v1/register',
        Content_Type => 'application/json',
        Content      => $serialized_data
    );

    print Dumper $res;
};

done_testing();

关键修改点说明

  1. 替换序列化方式:把freeze($datas)换成encode_json($datas),生成标准的JSON字符串,匹配Dancer2的JSON serializer要求
  2. 设置正确的请求头:在POST请求中添加Content_Type => 'application/json',明确告诉Dancer2这是一个JSON格式的请求体
  3. 规范请求体传递:用Content参数传递序列化后的JSON字符串,避免被HTTP::Request::Common当成表单参数错误解析

这样修改后,Dancer2就能正确解析请求体中的JSON数据,你的路由处理函数就能拿到完整的email和password值,也就不会触发数据库的非空约束错误了,和你用Postman测试的效果一致。

备注:内容来源于stack exchange,提问作者Kevin Lin

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.23 15:32:37