Weave Code
Code Weaver
Helps Laravel developers discover, compare, and choose open-source packages. See popularity, security, maintainers, and scores at a glance to make better decisions.
Feedback
Share your thoughts, report bugs, or suggest improvements.
Subject
Message

Phpunit Xml Laravel Package

lastdragon-ru/phpunit-xml

Tools for working with PHPUnit’s XML configuration: parse, build, and validate phpunit.xml files programmatically. Useful for CI automation, config generation, and upgrades/migrations between PHPUnit versions, with a focused API designed for PHP projects.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation Add the package via Composer:

    composer require --dev lastdragon-ru/phpunit-xml
    

    Ensure PHPUnit is configured in your phpunit.xml to autoload the package’s traits.

  2. First Use Case Import the XMLAssertions trait in your test class:

    use LastDragon\PHPUnitXML\XMLAssertions;
    use PHPUnit\Framework\TestCase;
    
    class XmlTest extends TestCase
    {
        use XMLAssertions;
    }
    

    Test XML equality against a schema or another XML string:

    public function testXmlStructure()
    {
        $xmlString = '<root><child>value</child></root>';
        $this->assertXmlStringEqualsXmlString($xmlString, $xmlString); // Basic equality
    }
    
  3. Where to Look First

    • Trait Documentation: Check the XMLAssertions trait for available methods (e.g., assertXmlStringMatchesSchema, assertXmlStringEqualsXmlString).
    • PHPUnit Manual: Review PHPUnit’s XML-related assertions for context (e.g., assertXmlStringEqualsXmlFile).
    • Examples: Look for usage in the package’s tests (if available) or community examples.

Implementation Patterns

Common Workflows

  1. Schema Validation Validate XML against an XSD schema:

    public function testXmlAgainstSchema()
    {
        $xml = '<catalog><book id="101"/></catalog>';
        $schema = file_get_contents('path/to/schema.xsd');
        $this->assertXmlStringMatchesSchema($xml, $schema);
    }
    
  2. Dynamic XML Assertions Useful for API responses or generated XML:

    public function testApiResponseXml()
    {
        $responseXml = $this->get('/api/data')->getContent();
        $expectedXml = '<response><status>success</status></response>';
        $this->assertXmlStringEqualsXmlString($expectedXml, $responseXml);
    }
    
  3. Partial XML Matching Assert specific nodes exist without strict equality:

    public function testPartialXmlMatch()
    {
        $xml = '<root><user><name>John</name></user></root>';
        $this->assertXmlStringContainsNode($xml, 'name');
    }
    
  4. Integration with Laravel Combine with Laravel’s HTTP tests:

    public function testXmlResponseFromRoute()
    {
        $response = $this->getJson('/xml-endpoint');
        $this->assertXmlStringEqualsXmlString(
            '<data><item>test</item></data>',
            $response->getContent()
        );
    }
    

Integration Tips

  • Custom Schemas: Store schemas in tests/Resources/schemas/ and reference them via file_get_contents().
  • Laravel Factories: Generate test XML using factories or seeders for reusable test data.
  • Error Handling: Wrap assertions in try-catch blocks to log detailed failure messages:
    try {
        $this->assertXmlStringMatchesSchema($xml, $schema);
    } catch (Exception $e) {
        $this->fail('Schema validation failed: ' . $e->getMessage());
    }
    

Gotchas and Tips

Pitfalls

  1. Namespace Conflicts Ensure XML namespaces in test strings match the schema. Use Lxml or SimpleXML to normalize namespaces if needed:

    $dom = new \DOMDocument();
    $dom->loadXML($xml);
    $normalized = $dom->saveXML();
    
  2. Whitespace Sensitivity XML assertions are strict about whitespace. Use DOMDocument::preserveWhiteSpace or trim strings:

    $this->assertXmlStringEqualsXmlString(
        trim($expected),
        trim($actual)
    );
    
  3. Schema Location Relative paths in schemas may break in CI/CD. Use absolute paths or file_exists() checks:

    $schemaPath = base_path('tests/Resources/schemas/schema.xsd');
    $this->assertFileExists($schemaPath);
    
  4. Large XML Files Avoid loading entire large XML files into memory. Stream or chunk assertions where possible.

Debugging Tips

  • Detailed Failures: Use var_dump() or dd() to inspect XML structure before assertions:
    $dom = new \DOMDocument();
    $dom->loadXML($xml);
    $this->assertEquals('expected', $dom->getElementsByTagName('tag')->item(0)->nodeValue);
    
  • Schema Validation Errors: Capture schema errors explicitly:
    $errors = [];
    $this->assertXmlStringMatchesSchema($xml, $schema, $errors);
    $this->assertEmpty($errors, implode("\n", $errors));
    

Extension Points

  1. Custom Assertions Extend the trait or create a wrapper for reusable logic:

    trait CustomXmlAssertions {
        protected function assertXmlHasNodeValue($xml, $nodePath, $expectedValue) {
            $dom = new \DOMDocument();
            $dom->loadXML($xml);
            $node = $dom->getElementsByTagName($nodePath)->item(0);
            $this->assertNotNull($node, "Node $nodePath not found");
            $this->assertEquals($expectedValue, $node->nodeValue);
        }
    }
    
  2. Laravel Service Providers Bind the trait to a test helper service for global access:

    // In a TestServiceProvider
    app()->singleton('xml-assertions', function () {
        return new class {
            public function assertXmlHasNode($xml, $nodeName) {
                // Custom logic
            }
        };
    });
    
  3. CI/CD Integration Add a pre-test hook to validate schemas:

    # In phpunit.xml
    <php>
        <ini name="assert.exception" value="1"/>
    </php>
    
Weaver

How can I help you explore Laravel packages today?

Conversation history is not saved when not logged in.
Prompt
Add packages to context
No packages found.
terminal42/code-quality-tools
codifyo/ts-generator-bundle
andydefer/laravel-cluster
testo/fiber
mintobit/jobqueue
a4sex/maintenance-bundle
a4sex/entity-date-update
a4sex/client-identifier
a4sex/base-utilites
a4sex/key-value-storage
a4sex/micro-status
chilldev/dependency-injection-extra
datinglibre/datinglibre-app-api
biberltd/corebundle
bricre/symfony-bundle-test
biberltd/logbundle
dominium/http-adapter-bundle
dominium/google-analytics
a4sex/auto-clean-entity
christhompsontldr/laravel-inky