41. Tests Unitaires avec Field Forge | Field Forge - Champs personnalisés, conçus pour la vitesse
Télécharger Se connecter

41. Tests Unitaires avec Field Forge

Stratégies pour écrire des tests PHPUnit qui interagissent avec les champs Field Forge.

Configuration des Données de Test

php
class ProductFieldsTest extends WP_UnitTestCase {

    private $post_id;

    public function setUp(): void {
        parent::setUp();

        // Create a test post
        $this->post_id = $this->factory->post->create( [
            'post_type'   => 'product',
            'post_title'  => 'Test Product',
            'post_status' => 'publish',
        ] );

        // Set field values
        update_field( 'price', '29.99', $this->post_id );
        update_field( 'sku', 'TEST-001', $this->post_id );
        update_field( 'is_featured', true, $this->post_id );
    }

    public function test_get_field_returns_price() {
        $price = get_field( 'price', $this->post_id );
        $this->assertEquals( '29.99', $price );
    }

    public function test_get_field_returns_boolean() {
        $featured = get_field( 'is_featured', $this->post_id );
        $this->assertTrue( $featured );
    }

    public function test_get_fields_returns_all() {
        $fields = get_fields( $this->post_id );
        $this->assertArrayHasKey( 'price', $fields );
        $this->assertArrayHasKey( 'sku', $fields );
    }

    public function test_delete_field_removes_value() {
        delete_field( 'sku', $this->post_id );
        $sku = get_field( 'sku', $this->post_id );
        $this->assertNull( $sku );
    }

    public function test_update_field_changes_value() {
        update_field( 'price', '39.99', $this->post_id );
        $price = get_field( 'price', $this->post_id );
        $this->assertEquals( '39.99', $price );
    }

    public function tearDown(): void {
        FIELDFORGE_Field_Values::instance()->delete_all( $this->post_id );
        wp_delete_post( $this->post_id, true );
        parent::tearDown();
    }
}

Tester les Champs Répéteurs

php
public function test_repeater_field() {
    $members = [
        [ 'name' => 'Alice', 'role' => 'Developer' ],
        [ 'name' => 'Bob', 'role' => 'Designer' ],
    ];

    $field_def = FIELDFORGE_Field_Groups::instance()->find_field( 'team_members', $this->post_id );
    FIELDFORGE_Field_Values::instance()->save_compound_field(
        'team_members', $members, $this->post_id, $field_def
    );

    $result = get_field( 'team_members', $this->post_id );
    $this->assertCount( 2, $result );
    $this->assertEquals( 'Alice', $result[0]['name'] );
    $this->assertEquals( 'Designer', $result[1]['role'] );
}

Assistant IA Forge En ligne

Bonjour ! Je suis l'assistant IA Field Forge. Posez-moi n'importe quelle question sur le plugin — configuration, fonctionnalités, dépannage ou développement.

À l'instant
Propulsé par Forge IA · Parcourir la documentation