Search code examples
perltestingmojolicious

Using TAP::Formatter::JUnit with Mojolicious tests?


I have a number of tests for my Mojolicious application and that all works fine, and now I'm trying to get Mojolicious to output to JUnit XML. I've found TAP::Formatter::JUnit which looks like it's exactly what I want, but I'm not grasping how to get the Mojolicious tests (run by just script/site.pl test from the root level of my application) to use that.

Am I missing something blindly obvious, or am I not able to use Mojolicious' built-in testing functionality if I want it outputted to JUnit XML?


Solution

  • I looked into Mojolicious::Command::test and it is using Test::Harness to run the test suite. The module is wrapper over TAP::Harness, whose formatter parameter we need to set. I haven't found any way how to push the parameter through (there are environment variables like HARNESS_OPTIONS, but they did not allow for the parameter).

    What you can do is to implement new command for your application. I created new Mojolicious application, added new command namespace per the guide above in application startup:

    push @{$self->commands->namespaces}, 'JUnitTest::Command';
    

    Then I just copied Mojolicious::Command::test into JUnit::Command::testjunit and replaced last lines of run method:

    $ENV{HARNESS_OPTIONS} //= 'c';
    require Test::Harness;
    Test::Harness::runtests(sort @args);
    

    with

    require TAP::Harness;
    my $harness = TAP::Harness->new({
      formatter_class => 'TAP::Formatter::JUnit',
      lib   => \@INC,
      merge => 1,
    });
    $harness->runtests(sort @args);
    

    Running it as

    perl script/junit_test testjunit
    

    resulted in this output:

    <testsuites>
      <testsuite failures="0" errors="0" tests="3" name="t_basic_t">
        <testcase name="1 - get /"></testcase>
        <testcase name="2 - 200 OK"></testcase>
        <testcase name="3 - content is similar"></testcase>
        <system-out><![CDATA[1..3
    ok 1 - get /
    ok 2 - 200 OK
    ok 3 - content is similar
    ]]></system-out>
        <system-err></system-err>
      </testsuite>
    </testsuites>
    

    Hope this helps.